我正在查看一些有关无法访问代码的自定义代码。简而言之,我有一个宏将某些代码标记为逻辑上不可访问。这可以用作:
int boolToInt(bool b)
{
switch (b)
{
case true: return 1;
case false: return 0;
}
MY_UNREACHABLE("All cases are covered within the switch");
}
同样,我试图在编译器已经知道代码无法访问的位置重用这个宏。
while (true)
{
if (++i == 42)
return j;
// ...
}
MY_UNREACHABLE("Infinite loop that always returns/continues, never breaks");
也就是说,在某些情况下,MSVC 仍然会在无法访问的宏中对自定义处理给出无法访问的代码警告。简化版本如下所示:
// MSVC: cl.exe /std:c++latest /W4
// Clang: clang++ -O3 -std=c++2a -stdlib=libc++ -Weverything
#ifdef __clang__
#pragma clang diagnostic ignored "-Wc++98-compat"
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#pragma clang diagnostic warning "-Wunreachable-code"
#else
#pragma warning( default: 4702 )
#endif
#ifdef __clang__
#define DISABLE_WARNING_UNREACHABLE _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wunreachable-code\"")
#define REENABLE_WARNING_UNREACHABLE _Pragma("clang diagnostic pop")
#else
#define DISABLE_WARNING_UNREACHABLE __pragma(warning(push)) __pragma(warning( disable : 4702 ))
#define REENABLE_WARNING_UNREACHABLE __pragma(warning(pop))
#endif
[[noreturn]] void g();
#define MY_UNREACHABLE(msg) DISABLE_WARNING_UNREACHABLE; g() REENABLE_WARNING_UNREACHABLE
[[noreturn]] void my_exit(int);
[[noreturn]] void f()
{
my_exit(0);
//g(); // Test if warning works without the macro
MY_UNREACHABLE("Custom message");
}
根据我从[微软文档](https://docs.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword?view=vs-2019)中了解到的信息,我应该能够__pragma
在调用我的宏时使用带有此警告的 push/pop 来禁用此警告。(它甚至有一个这样做的例子)
这里应该改变什么来抑制 MSVC 中的警告?