不允许以下内容('std :: numeric_limits :: max()'不能出现在常量表达式中):
#include <limits>
struct MyStruct {
private:
static const unsigned int INVALID_VALUE = std::numeric_limits<unsigned int>::max();
public:
unsigned int index;
inline MyStruct() : index(INVALID_VALUE) {}
};
这可能是获得所需行为的最佳方式?如果可能的话,我希望在编译时知道INVALID_VALUE(例如,允许编译器进行更好的优化)。
答案 0 :(得分:2)
您可以使用<climits>
中的UINT_MAX
代替。
或者,您可以提供定义:
struct MyStruct
{
private:
static const unsigned int INVALID_VALUE;
};
const unsigned int MyStruct::INVALID_VALUE = std::numeric_limits<unsigned int>::max();
或者,切换到函数为constexpr
的C ++ 11,这没问题。
答案 1 :(得分:1)
如何将常量定义为~0U
。由于unsigned int
被定义为&#34;直接二进制表示&#34;,因此其反转应为所有位设置。
答案 2 :(得分:1)
在C ++ 11或更高版本中,这应该没问题,因为现在numeric_limits
函数被声明为constexpr
。
如果你被困在过去,那么你需要在课堂外定义和初始化常量:
// Header file
struct MyStruct {
static const unsigned int INVALID_VALUE;
// ...
};
// One source file
const unsigned int Mystruct::INVALID_VALUE = std::numeric_limits<unsigned int>::max();
或者,您可以使用UINT_MAX
中定义的<climits>
宏。这样做的好处是你的常量可用于常量表达式。
答案 3 :(得分:0)
添加:
const unsigned int mystruct::INVALID_VALUE = std::numeric_limits<unsigned int>::max();
在cpp文件中的某个地方,这是初始化静态成员的常规方法。