通过 numeric_limits 为枚举分配最大值?
Assigning an enum a max value via numeric_limits?
我在分配 enum
最大值中的元素时遇到问题。第一:
protected:
enum {DEFAULT_PADDING=std::numeric_limits<enum>::max()};
结果:
./basecode.h:30:51: error: expected identifier or '{'
enum {DEFAULT_PADDING=std::numeric_limits<enum>::max()};
^
./basecode.h:30:59: error: expected a type
enum {DEFAULT_PADDING=std::numeric_limits<enum>::max()};
(and a couple of others)
二、切换到:
protected:
enum {DEFAULT_PADDING=std::numeric_limits<unsigned int>::max()};
结果:
./basecode.h:30:27: error: expression is not an integral constant expression
enum {DEFAULT_PADDING=std::numeric_limits<unsigned int>::max()};
如何让 numeric_limits
给我一个可以在编译时用于 enum
的值?
该库较旧,因此它支持许多较旧的编译器和 IDE。我需要至少是 C++03,最好是 C++98 的东西。
标准注意事项适用:这是一个简单的基于 make 的项目。不使用Autotools,不使用Cmake,不使用Boost等
在 C++03 中,std::numeric_limits<T>::max()
就是 static
。在 C++11 中,它变成了 static constexpr
。您需要后者才能在整数常量表达式中使用,因此只需使用 -std=c++11
进行编译即可。
如果你不能使用C++11,你可以使用UINT_MAX
。
我在分配 enum
最大值中的元素时遇到问题。第一:
protected:
enum {DEFAULT_PADDING=std::numeric_limits<enum>::max()};
结果:
./basecode.h:30:51: error: expected identifier or '{'
enum {DEFAULT_PADDING=std::numeric_limits<enum>::max()};
^
./basecode.h:30:59: error: expected a type
enum {DEFAULT_PADDING=std::numeric_limits<enum>::max()};
(and a couple of others)
二、切换到:
protected:
enum {DEFAULT_PADDING=std::numeric_limits<unsigned int>::max()};
结果:
./basecode.h:30:27: error: expression is not an integral constant expression
enum {DEFAULT_PADDING=std::numeric_limits<unsigned int>::max()};
如何让 numeric_limits
给我一个可以在编译时用于 enum
的值?
该库较旧,因此它支持许多较旧的编译器和 IDE。我需要至少是 C++03,最好是 C++98 的东西。
标准注意事项适用:这是一个简单的基于 make 的项目。不使用Autotools,不使用Cmake,不使用Boost等
在 C++03 中,std::numeric_limits<T>::max()
就是 static
。在 C++11 中,它变成了 static constexpr
。您需要后者才能在整数常量表达式中使用,因此只需使用 -std=c++11
进行编译即可。
如果你不能使用C++11,你可以使用UINT_MAX
。