c++ - 模板化的 constexpr 变量

标签 c++ templates c++17 constexpr

这个问题在这里已经有了答案:





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/

相关文章:

c++ - 如何使用访问者从变体返回特定类型?

c++ - 如何使用 -std=c++17(可选、任意、string_view、变体)在 g++ 6.2.0 中包含 C++ 17 header

c++ - 单例还是信号和槽?

c++ - 什么时候使用模板显式实例化?

c++ - 在继承模板类中使用下标[]运算符

c++ - 努力使用模板化结构选择类型

c++ - 如何用 1000000 个元素声明类 C++

c++ - 如何将 boost::asio::ip::tcp::v4 打印到标准输出

javascript - 递归地迭代一个对象并将父级附加到每个子级

c++ - std::Optional 怎么永远不会 "valueless by exception"?