这个问题在这里已经有了答案:
Forward declare a constexpr variable template
(2 个回答)
5 个月前关闭。
我想确认这段代码是合法的(或不合法的?)C++17。
#include <iostream>
template<int N> inline constexpr float MyConst;
template<> inline constexpr float MyConst<1> = 1.1f;
template<> inline constexpr float MyConst<2> = 2.2f;
int main ()
{
std::cout << MyConst<1> << '\n';
return 0;
}
如果由 编译,我不会出错(并得到正确的输出) g++ 和 MSVC ,但是 英特尔 和 叮当给出错误:
test.cpp(3): error: missing initializer for constexpr variable
template<int N> inline constexpr float MyConst;
^
编译 -std=c++17
( /std:c++17
对于 MSVC)。在 Godbolt 和我的本地机器上尝试了最新的编译器。
最佳答案
一个 constexpr
变量必须立即初始化。因此 MyConst
的模板需要一个初始化程序/定义。 GCC 在第一次出现时不需要定义,这违反了规范。如果您使用变量的非特殊形式,例如MyConst<3>
you will get a similar error from GCC :
<source>: In instantiation of 'constexpr const float MyConst<3>':
<source>:10:18: required from here
<source>:3:40: error: uninitialized 'const MyConst<3>' [-fpermissive]
3 | template<int N> inline constexpr float MyConst;
| ^~~~~~~
ASM generation compiler returned: 1
<source>: In instantiation of 'constexpr const float MyConst<3>':
<source>:10:18: required from here
<source>:3:40: error: uninitialized 'const MyConst<3>' [-fpermissive]
3 | template<int N> inline constexpr float MyConst;
|
这可以通过为 MyConst 提供初始定义来解决,例如// Use a "sensible default"
template<int N> inline constexpr float MyConst(0.0f);
// Provide a more general definition
template<int N> inline constexpr float MyConst = N*1.1f;
标准相关部分见dcl.constexpr paragraph 1 .The constexpr specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template. The consteval specifier shall be applied only to the declaration of a function or function template. A function or static data member declared with the constexpr or consteval specifier is implicitly an inline function or variable. If any declaration of a function or function template has a constexpr or consteval specifier, then all its declarations shall contain the same specifier.
关于c++ - 模板化的 constexpr 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67319502/