Using numeric_limits::max() in constant expressions

前端 未结 5 849
無奈伤痛
無奈伤痛 2020-12-10 11:04

I would like to define inside a class a constant which value is the maximum possible int. Something like this:

class A
{
    ...
    static const int ERROR_V         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-10 11:30

    While the current standard lacks support here, for integral types Boost.IntegerTraits gives you the compile time constants const_min and const_max.

    The problem arises from §9.4.2/4:

    If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions.

    Note that it adds:

    The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

    As others already mentioned numeric_limits min() and max() simply aren't integral constant expressions, i.e. compile time constants.

提交回复
热议问题