Why should I prefer static constexpr int in a class over enum for class-level integral constants?

后端 未结 3 1295
我寻月下人不归
我寻月下人不归 2021-02-14 08:18

C++17 Update: static constexpr variables are implicitly inline so there\'s no external definition necessary.


Original qu

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-14 09:00

    Perhaps no advantage for your usage because you're just using simple fixed integer values.

    But, [AFAIK] constexpr can be more general as it allows initialization from anything that can be evaluated at compile time.

    From type_traits:

     /// integral_constant
      template
        struct integral_constant
        {
          static constexpr _Tp                  value = __v;
          typedef _Tp                           value_type;
          typedef integral_constant<_Tp, __v>   type;
          constexpr operator value_type() const { return value; }
    #if __cplusplus > 201103L
    #define __cpp_lib_integral_constant_callable 201304
          constexpr value_type operator()() const { return value; }
    #endif
        };
    

    Thus, constexpr has usage in metaprogramming.

    The following is a bit rough.

    If you had a function like:

    constexpr unsigned
    bitmask(int bitno)
    {
    
        return 1u << bitno;
    }
    

    You might find a usage such as:

    constexpr unsigned BIT_0 = bitmask(0);
    constexpr unsigned BIT_1 = bitmask(1);
    

提交回复
热议问题