作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果有一个模板 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
, orconsteval
specifiers.
(强调我的)
这正是 GCC 错误消息所说的内容。
Clang 的错误消息说显式实例化中缺少 const
,并添加它
template size_t const fib<70>; // ok everywhere
是否允许 Clang compile代码也是如此。
关于c++ - 如何在 C++ 中显式实例化模板 constexpr 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69047064/
我是一名优秀的程序员,十分优秀!