gpt4 book ai didi

在 gcc 9.3 中编译但不能在 gcc 10.2 中编译的 C++ 代码

转载 作者:行者123 更新时间:2023-12-02 02:21:51 33 4
gpt4 key购买 nike

以下代码可以在 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()不是常量表达式

哪个编译器是正确的? 9.3 还是 10.2?

如果 10.2 是正确的,我如何定义编译时数组并将其大小(和数组)作为参数传递?

最佳答案

不确定哪一个是正确的,但是对于

how can I define a compile time array and pass its size (and the array) as an argument?

您可以将函数更改为

template <typename T, std::size_t N>
constexpr auto f(const std::array<T, N>& arr)
{
std::array<int, N> res{};
return res;
}

现在大小被提升到模板参数中。

关于在 gcc 9.3 中编译但不能在 gcc 10.2 中编译的 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66306108/

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