如何声明constexpr extern? [英] How to declare constexpr extern?
问题描述
是否可以声明变量 extern constexpr
并将其定义在另一个文件中?
Is it possible to declare a variable extern constexpr
and define it in another file?
我尝试过但是编译器给出错误:
I tried it but the compiler gives error:
constexpr
变量'<$ c $的声明c> i '不是定义
在.h中:
extern constexpr int i;
in .cpp:
constexpr int i = 10;
推荐答案
不行,这就是标准说(第7.1.5节):
no you can't do it, here's what the standard says (section 7.1.5):
1 constexpr说明符应仅应用于
变量的定义或变量模板,函数或
函数模板的声明,或
文字类型(3.9)的静态数据成员的声明。如果函数,函数
模板或变量模板的任何声明具有constexpr说明符,则其所有
声明均应包含constexpr说明符。 [注意:
的显式专业化可以与$ exp $到constexpr指定符的模板声明不同。函数参数不能声明为
constexpr。 —尾注]
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 ]
标准提供的一些示例:
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
这篇关于如何声明constexpr extern?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!