Static constexpr int vs old-fashioned enum: when and why?

前端 未结 3 1551
甜味超标
甜味超标 2020-12-15 03:53

This is maybe a basic question, but I cannot see the response by myself right now.

Consider the following code:

template
struct T {
            


        
3条回答
  •  臣服心动
    2020-12-15 04:31

    The currently accepted answer by SergeyA no longer holds as of C++17 (Definitions and ODR).

    Every declaration is a definition, except for the following:

    • ...
    • (deprecated) Namespace scope declaration of a static data member that was defined within the class with the constexpr specifier
    struct S {
        static constexpr int x = 42; // implicitly inline, defines S::x
    };
    constexpr int S::x; // declares S::x, not a redefinition
    

    Hence, as of C++17, I would use the static constexpr definition which is more expressive than the enum.

提交回复
热议问题