私はvectorやpairのような標準的なコンテナをテンプレート引数としてカスタム型を使って作業しています。テンプレート型パラメータのC++ const
std::vector<const std::pair<const customType, const double>>
ハッシュ()演算子と比較演算子==と<が定義されています。ほとんどの時間、これらのテンプレートの種類はのように、const修飾されています。
partial_sort_copy、partial_sort、eraseなどの標準ライブラリ関数にこのような値を渡すと問題が発生します。何らかの理由で、これらの関数は最終的には与えられた型の代入を試みますが、最終的にはconstのためにコンパイルに失敗します。
ベクターとペアのテンプレートタイプにconstをキャストする方法はありますか?すなわち、キャストvector<const myType>
~vector<myType>
。
ありがとうございます。
EDIT:最小のサンプルコードが衝突しました!
// Non-working code:
std::vector<const std::pair<const int, const double>> list{ { 3, 3. }, { 2, 2. }, { 1, 1. }, { 0, 0. } };
std::partial_sort(list.begin(), list.begin() + 2, list.end(), [](const std::pair<const int, const double>& x, const std::pair<const int, const double>& y){ return x.first < y.first; });
// This works, actually:
std::vector<std::pair<int, double>> list{ { 3, 3. }, { 2, 2. }, { 1, 1. }, { 0, 0. } };
std::partial_sort(list.begin(), list.begin() + 2, list.end(), [](const std::pair<int, double>& x, const std::pair<int, double>& y){ return x.first < y.first; });
標準ライブラリが気に入らないコードについて教えてください。
おそらく、const以外の値のconst値を使用してください。おそらくADLの利用可能な 'swap'を定義するのが助けになるかもしれませんが、' std :: pair'をサブクラス化する必要があります。これは 'std'に何かを定義するのは良い考えではないからです。 – bipll
あなたの答えに感謝します。私はADLを調べます。 – jvier
@bipll std名前空間で 'swap'や' hash'のような関数のオーバーロード/テンプレートを定義することはまったく認められています。 – Johan