gpt4 book ai didi

c++ - 如何使用 std::copy 将一个 constexpr 数组复制到另一个 constexpr 数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:42 24 4
gpt4 key购买 nike

在下面的代码中,我创建了一个长度为 6 的数组,并在前 3 个元素中使用 1、2 和 3 对其进行了初始化。然后我将前 3 个元素复制到后 3 个元素。然后我按顺序打印所有元素。

std::array<int, 6> bar = {1, 2, 3};

int main(){
// Copy the first 3 elements to the last 3 elements
std::copy(bar.begin(), bar.end() - 3, bar.end() - 3);

// Print all the elements of bar
for(auto& i: bar) std::cout << i << std::endl;
}

它工作正常,但是当我尝试创建数组 constexpr 时,它不再编译:

constexpr std::array<int, 6> bar = {1, 2, 3};

int main(){
// Copy the first 3 elements to the last 3 elements
std::copy(bar.begin(), bar.end() - 3, bar.end() - 3); // Won't compile!

// Print all the elements of bar
for(auto& i: bar) std::cout << i << std::endl;
}

使用 g++ -std=c++14 main.cpp -o main 编译我收到以下错误消息:

/usr/include/c++/5/bits/stl_algobase.h: In instantiation of ‘_OI std::__copy_move_a(_II, _II, _OI) [with bool _IsMove = false; _II = const int*; _OI = const int*]’:
/usr/include/c++/5/bits/stl_algobase.h:438:45: required from ‘_OI std::__copy_move_a2(_II, _II, _OI) [with bool _IsMove = false; _II = const int*; _OI = const int*]’
/usr/include/c++/5/bits/stl_algobase.h:471:8: required from ‘_OI std::copy(_II, _II, _OI) [with _II = const int*; _OI = const int*]’
main.cpp:115:53: required from here
/usr/include/c++/5/bits/stl_algobase.h:402:44: error: no matching function for call to ‘std::__copy_move<false, true, std::random_access_iterator_tag>::__copy_m(const int*&, const int*&, const int*&)’
_Category>::__copy_m(__first, __last, __result);
^
/usr/include/c++/5/bits/stl_algobase.h:373:9: note: candidate: template<class _Tp> static _Tp* std::__copy_move<_IsMove, true, std::random_access_iterator_tag>::__copy_m(const _Tp*, const _Tp*, _Tp*) [with _Tp = _Tp; bool _IsMove = false]
__copy_m(const _Tp* __first, const _Tp* __last, _Tp* __result)
^
/usr/include/c++/5/bits/stl_algobase.h:373:9: note: template argument deduction/substitution failed:
/usr/include/c++/5/bits/stl_algobase.h:402:44: note: deduced conflicting types for parameter ‘_Tp’ (‘int’ and ‘const int’)
_Category>::__copy_m(__first, __last, __result);

我完全不明白这个错误信息。 std::copy 不是 constexpr 吗?如果不是,应该是,对吧?如果 std::copyconstexpr,我的代码会工作吗?

最佳答案

你应该创建一个 constexpr 函数。 constexpr 表示 const,但不在 constexpr 函数的范围内。

constexpr auto get_bar() {
std::array<int, 6> bar = {1, 2, 3, 0, 0, 0};

copy(bar.begin(), bar.end() - 3, bar.end() - 3);

return bar;
}

但是,您需要编写自己的 copy 版本,因为它在标准库中没有标记为 constexpr

更改编译时数组的值没有意义,这与要求编译器在运行时更改变量类型是一回事。编译器在运行时甚至不存在。但是,constexpr 函数由编译器执行,因此要求它改变值仍然有意义。这就是为什么上面的代码有意义。

请注意,大多数 std::array 访问器在 C++17 之前不是 constexpr

关于c++ - 如何使用 std::copy 将一个 constexpr 数组复制到另一个 constexpr 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41600157/

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