Why is C++ numeric_limits<enum_type>::max() == 0?

折月煮酒 提交于 2019-11-30 01:49:59

问题


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.


回答1:


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.




回答2:


For non-specialized versions of the template, max returns T(). You have not written a numeric_limits specialization for your test type, so you get the default implementation.




回答3:


The numeric_limits<T> is a regular class template, it is not connected to the compiler in any special way as to find out about user-defined enum types. If you look at the <limits> file, it has the default template definition that returns zeros for everything, and a whole bunch of type-specific specifications for the individual types, returning the right constants.

You can "plug in" your enum into numeric_limits by providing a specification of numeric_limits<test> by yourself. You can copy the one for int from the <limits>, and modify it to suit your needs.




回答4:


From the C++11 draft:

In 18.3.2.1, about numeric_limits:

Non-arithmetic standard types, such as complex (26.4.2), shall not have specializations.

And an enum is not an arithmetic standard type.

Then, in the non-specialized template:

template<class T> class numeric_limits {
    public:
    [...]
    static constexpr bool is_specialized = false;
    static constexpr T max() noexcept { return T(); }
};

That is, the non-specialized max() function returns the default initialized value for that type, that is 0.



来源:https://stackoverflow.com/questions/9201865/why-is-c-numeric-limitsenum-typemax-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!