以下代码在 Visual Studio 2010 中生成警告 C4127(条件表达式为常量)(其中 alias_wchar_t 是 wchar_t 的别名):
if (sizeof(alias_wchar_t) == sizeof(wchar_t)) // warning occurs here
{
// do stuff
}
else
{
// do other stuff
}
除了抑制警告之外,解决此问题的最优雅方法是什么?
我想出的最佳解决方案是将条件填充到静态 bool 值中,并将其用作条件。 if-else 上面和下面有大量代码,所以我将整个代码用大括号括起来,以尽可能地限制变量的范围:
// <snip>
{
static bool isSameSize = (sizeof(alias_wchar_t) == sizeof(wchar_t));
if (isSameSize)
{
// do stuff
}
else
{
// do other stuff
}
}
// <snip>
这感觉很恶心。这似乎应该在编译时而不是运行时解决,但预处理器不知道 sizeof。有没有更干净、更优雅的方法来解决这个问题?
最佳答案
What's the most elegant way to resolve this, short of suppressing the warning?
条件在编译时是已知的,因此您也可以在编译时进行检查。不要使用 if
,只需让编译器插入对正确函数的调用即可。这是一个完整的例子:
#include <iostream>
typedef short alias_wchar_t; // for testing
template<bool Condition>
struct DoStuff
{
};
template<>
struct DoStuff<true>
{
static void doStuff()
{
std::cout << "sizeof(alias_wchar_t) == sizeof(wchar_t)\n";
}
};
template<>
struct DoStuff<false>
{
static void doStuff()
{
std::cout << "sizeof(alias_wchar_t) != sizeof(wchar_t)\n";
}
};
void doStuff()
{
DoStuff<sizeof(alias_wchar_t) == sizeof(wchar_t)>::doStuff();
}
int main()
{
doStuff();
}
我会说,这是否真的比您的原始代码更优雅(仅针对该编译单元关闭了特定的编译器警告)是基于意见的。
无论如何,在 /W4
中使用 VC 2013 编译时没有警告。
关于c++ - C4127:条件表达式为常数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25573996/