次のコードでは、長さ6の配列を作成し、最初の3つの要素に1、2、3で初期化します。次に、最初の3つの要素を最後の3つの要素にコピーします。次に、すべての要素を順番に印刷します。std :: copyを使って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);
// Print all the elements of bar
for(auto& i: bar) std::cout << i << std::endl;
}
それは正常に動作しますが、私は、配列constexpr
を作るしようとすると、それは、もはやコンパイルしません:
g++ -std=c++14 main.cpp -o main
してコンパイル
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;
}
私は、次のエラーメッセージが出ます:
/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を宣言するのは意味がありません。どちらの配列も一定であるかどうか。 – Phil1970
@lateeveloperどのように私は 'const'ではないコンパイル時にものを作る? –