在下面的代码中,我创建了一个长度为 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
not constexpr
?如果不是,那也应该是吧?如果我的代码可以工作吗std::copy
was constexpr
?