How to declare constexpr extern?

前端 未结 6 924
耶瑟儿~
耶瑟儿~ 2020-11-29 07:43

Is it possible to declare a variable extern constexpr and define it in another file?

I tried it but the compiler gives error:

De

6条回答
  •  既然无缘
    2020-11-29 08:21

    no you can't do it, here's what the standard says (section 7.1.5):

    1 The constexpr specifier shall be applied only to the definition of a variable or variable template, the declaration of a function or function template, or the declaration of a static data member of a literal type (3.9). If any declaration of a function, function template, or variable template has a constexpr specifier, then all its declarations shall contain the constexpr specifier. [Note: An explicit specialization can differ from the template declaration with respect to the constexpr specifier. Function parameters cannot be declared constexpr. — end note ]

    some examples given by the standard:

      constexpr void square(int &x);  // OK: declaration
      constexpr int bufsz = 1024;  // OK: definition
      constexpr struct pixel {  // error: pixel is a type
        int x;
        int y;
        constexpr pixel(int);  // OK: declaration
      };
    
      extern constexpr int memsz; // error: not a definition
    

提交回复
热议问题