大佬教程收集整理的这篇文章主要介绍了在 gcc 9.3 中编译但不在 gcc 10.2 中编译的 C++ 代码,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
以下代码可以在 gcc 9.3 中编译,但不能在 gcc 10.2 中编译:
constexpr std::array<int,2> opt = {1,2};
template <typename T>
constexpr auto f(const T& arr)
{
std::array<int,arr.size()> res{};
return res;
}
int main()
{
auto res = f(opt);
}
代码在 https://godbolt.org/z/8hb6M8 中。
gcc10.2 给出的错误是 arr.size() is not a constant Expression
。
哪个编译器是对的? 9.3 还是 10.2?
如果 10.2 是正确的,@R_489_11399@定义编译时数组并将其大小(和数组)作为参数传递?
不确定哪个是正确的,但对于
如何定义编译时数组并将其大小(和数组)作为参数传递?
您可以将功能更改为
template <typename T,std::size_t N>
constexpr auto f(const std::array<T,N>& arr)
{
std::array<int,N> res{};
return res;
}
现在大小被提升到模板参数中。
,另一种在两种编译器中都适用且不需要更改模板声明的替代方法:
init
,
从 C++20 开始,常量表达式的定义发生了变化,您可以在 this 上找到一些变化。
更简短的答案是更改您的函数签名:
template <typename T>
constexpr auto f(const T& arr);
进入:
template <typename T>
constexpr auto f(const T arr);
然后它works。
以上是大佬教程为你收集整理的在 gcc 9.3 中编译但不在 gcc 10.2 中编译的 C++ 代码全部内容,希望文章能够帮你解决在 gcc 9.3 中编译但不在 gcc 10.2 中编译的 C++ 代码所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。