In a type trait, why do people use enum rather than static const for the value?

前端 未结 5 1860
别那么骄傲
别那么骄傲 2021-02-04 02:28

For example, this is how I would write it, and it compiles and works just fine:

template struct is_pointer {
  static const bool valu         


        
5条回答
  •  悲&欢浪女
    2021-02-04 03:16

    Some people write the less obvious enum rather than static bool const because they don't realize that there are other changes they should make.

    C++ requires the object to be defined if it's address is needed, for example if it's passed to this function foo:

    void foo(bool const &);
    

    However, solving the issue by defining the object is actually not the correct fix for this problem. Here are some alternatives:

    1. Small objects should not be passed by reference. The change should be to remove const & from the function signature, not add a definition for the object.

    2. Where the function signature cannot be changed, a temporary can be created explicitly in the call: foo( bool { Cls::mbr } )

    3. However, this is compile time information! Therefore foo should be a template with a T and T* overload, or be specialized with bool.

    This 3rd solution has the benefit of removing an unnecessary run time check (hopefully optimized by the compiler) and also allowing for the pointer and non-pointer case to be handled independently, possibly making the code clearer.

提交回复
热议问题