c++ - 如何在 C++ 中显式实例化模板 constexpr 变量?

标签 c++ language-lawyer constexpr explicit-instantiation

如果有一个模板 constexpr 变量(例如,用于计算 Fibonacci 数列)并且想为某个模板参数实例化它,在实例化期间必须重复 constexpr 关键字吗?

template<int N> constexpr size_t fib = fib<N-1> + fib<N-2>;
template<> constexpr size_t fib<1> = 1;
template<> constexpr size_t fib<2> = 1;

//template constexpr size_t fib<70>; // GCC error
template size_t fib<70>; // Clang error

这里的问题是 GCC 坚持删除关键字:

error: explicit instantiation shall not use 'constexpr' specifier

虽然 Clang 坚持保留它:

error: type 'size_t' (aka 'unsigned long') of explicit instantiation of 'fib' does not match expected type 'const size_t' (aka 'const unsigned long')

演示:https://gcc.godbolt.org/z/f6rMjz95E

根据标准,这里哪个编译器是正确的?

最佳答案

这可能是一个 Clang 错误。来自 temp.explicit#3

... An explicit instantiation of a function template, member function of a class template, or variable template shall not use the inline, constexpr, or consteval specifiers.

(强调我的)

这正是 GCC 错误消息所说的内容。

Clang 的错误消息说显式实例化中缺少 const,并添加它

template size_t const fib<70>;  // ok everywhere

是否允许 Clang compile代码也是如此。

关于c++ - 如何在 C++ 中显式实例化模板 constexpr 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69047064/

相关文章:

c++ - 套接字标识符等于 -1

javascript - ES6 中 block 级函数的精确语义是什么?

c++ - C++20 的 std::vector 是如何分配 constexpr 的?

c++ - 什么时候需要 R 值引用?

c++ - 可变参数模板无法识别 constexpr 函数

c++ - C++14 标准中哪里说不能在 constexpr 函数的定义中使用非 constexpr 函数?

java - Protobuf C++ 与 Android Java

c++ - 如何将我自己的文件关联添加到 "Open with"上下文菜单中?

c++ - 在 Windows : Cannot open include file: 'Magick++.h' : No such file or directory 中编译 ZBar 示例时出错

c++ - 对于什么 T `std::declval<T>()` 没有匹配函数?