gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:39:34 24 4
gpt4 key购买 nike

如果有一个模板 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com