为什么是C ++ numeric_limits< enum_type> :: max()== 0? [英] Why is C++ numeric_limits<enum_type>::max() == 0?
问题描述
这里有一些代码看起来像是可以工作的:
#include< cassert>
#include< limits>
enum test {A = 1};
int main()
{
int max = std :: numeric_limits< test> :: max();
assert(max> 0);但是它在GCC(4.6.2)和clang(2.9)下都失败了,在Linux上:max()对于枚举类型其实是零!即使你使用C ++ 11枚举类型说明符来明确说明你想要的枚举类型,这也是正确的。
为什么是这样的?至于C ++ 11的行为,它是一个明确要求的东西?
解决方案 std: :numeric_limits
专用于标准库中的每个算术类型,包括浮点和整数,包括 bool
(§18.3.2.1/ 2 )。
您的枚举 test 不是这些类型之一,因此使用主模板。它的行为由§18.3.2.3/ 1规定:默认的 numeric_limits< T>
模板应具有所有成员,但 0
或 false
值。
如果您想了解底层类型 test
,您可以使用 underlying_type
:
std :: numeric_limits< std :: underlying_type< test> :: type> :: max()
b $ b
或者,您可以专门化 numeric_limits
为 test
并返回您想要的值。这不是一个特别好的主意,
Here's a bit of code that might seem like it would work:
#include <cassert>
#include <limits>
enum test { A = 1 };
int main()
{
int max = std::numeric_limits<test>::max();
assert(max > 0);
}
But it fails under both GCC (4.6.2) and clang (2.9) on Linux: max() for enum types is in fact zero! And this remains true even if you use the C++11 enum type specifier to explcitly say what type you want your enum to have.
Why is this? And as for the C++11 behavior, is it something explcitly called for? I could find no mention of it in N2347, the paper on Strongly Typed Enums.
解决方案 std::numeric_limits
is specialized in the Standard Library "for each arithmetic type, both floating point and integer, including bool
" (§18.3.2.1/2).
Your enumeration test
is not one of these types, so the primary template is used. Its behavior is specified by §18.3.2.3/1: "The default numeric_limits<T>
template shall have all members, but with 0
or false
values."
If you want to know the traits of the underlying type of test
, you can use underlying_type
:
std::numeric_limits<std::underlying_type<test>::type>::max()
Alternatively, you can specialize numeric_limits
for test
and have it return the values you want. This is not a particularly good idea, though.
这篇关于为什么是C ++ numeric_limits< enum_type> :: max()== 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!