std::pair
とその種類の値の1つの値をとる関数テンプレートがあります。私はstd::map
からのエントリをペア引数として使ってこの関数を呼びたいと思います。テンプレート引数の控除でconst/non-constの競合を解決する方法
#include <map>
#include <utility>
template <typename T1, typename T2>
void do_stuff(std::pair<T1, T2> const &pair, T1 const &val) {
// Imagine that this does something important...
}
int main() {
std::map<int, float> foo { { 0, 0.0 } };
do_stuff(*foo.begin(), 0);
}
これは、マップのエントリのタイプはstd::pair<const int, float>
ので、T1
のための型推論は、競合のタイプを持っているので、コンパイルに失敗します。const int
pair
引数、およびint
経由val
引数を経由して。
test.cc: In function ‘int main()’:
test.cc:12:27: error: no matching function for call to ‘do_stuff(std::pair<const int, float>&, int)’
do_stuff(*foo.begin(), 0);
^
test.cc:5:6: note: candidate: template<class T1, class T2> void do_stuff(const std::pair<_T1, _T2>&, const T1&)
void do_stuff(std::pair<T1, T2> const &pair, T1 const &val) {
^~~~~~~~
test.cc:5:6: note: template argument deduction/substitution failed:
test.cc:12:27: note: deduced conflicting types for parameter ‘const T1’ (‘const int’ and ‘int’)
do_stuff(*foo.begin(), 0);
^
この競合を解決するにはどうすればよいですか?理想的には、T1
をint
と推測したいと思いますが、実装がより簡単な場合はconst int
にしても問題ありません。場合
void do_stuff(std::pair<T1, T2> const &pair, typename std::remove_const<T1>::type const &val) {
が、私はより適切であるそれらのどれかわからない、または:
私はval
パラメータの種類のいずれかstd::remove_const
またはstd::decay
を使用して、エラーを解決できることを発見しました他にも良い方法があります。
わかりません...それに応じてdo_stuff()を定義してください。 'テンプレート void do_stuff(std :: pair const&pair、T1 const&val)'? –
max66
@ max66、私も最初の型*が* constではないペアでも動作したいです。 (パラメータ全体がconst参照によって渡されるので、ペアのメンバのconstanceは無関係です; constまたはnon-constのどちらかを許可する必要があります) – Wyzard
マップで構築しようとしましたか?あなたはこれをあまりにも遠くに持っていました – mtb