【发布时间】:2017-05-26 19:00:09
【问题描述】:
在下面的代码中,我创建了一个长度为 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::copy 是constexpr,我的代码会起作用吗?
【问题讨论】:
-
如果数组是const,则不能更改。
-
我对新的 C++ 特性没有太多经验,但是如果你想在之后修改它,声明一个数组 constexpr 是没有意义的。要么,数组是常量,要么不是。
-
@latedeveloper 如何在编译时制作不是 'const' 的东西?
-
@WillyGoat - 正是……你想在编译时做什么?复制数组中的值列表?
-
@Willy 我不明白你在问什么。
标签: c++ arrays algorithm c++11 constexpr