クラステンプレートがあります。const_iterator
このクラス テンプレート内で、sのコレクションでsを受け入れるメンバー関数テンプレートを定義しようとしていますstring
。コレクション自体は任意の種類の StdLib コレクションにすることができますが、現実的には か のいずれかになりvector
ますlist
。
コレクションは任意の型になる可能性があるため、template-template
パラメーターを使用してコレクションの型を指定しています。ただし、常に のコレクションになりstring
ます。メンバー関数を呼び出すときにコレクションの型を指定する必要がないように、テンプレートの引数推定が機能するようにします。
私の意図したユースケースに似た SSCCE に続くコード。
これまでのところ、クラス定義 ( Live Demo ) は次のとおりです。
template <typename Foo>
struct Gizmo
{
Foo mF;
Gizmo (Foo f) : mF (f) {};
template <template <typename> class Cont> void DoIt(
typename Cont <string>::const_iterator begin,
typename Cont <string>::const_iterator end)
{
stringstream ss;
ss << "(" << this->mF << ")\n";
const std::string s = ss.str();
copy (begin, end, ostream_iterator <std::string> (cout, s.c_str()));
}
};
クラス テンプレートのインスタンス化のコンパイルが成功します。
int main()
{
list <string> l;
l.push_back ("Hello");
l.push_back ("world");
Gizmo <unsigned> g (42);
}
しかし、引数の演繹法を活用しようとすると (それがなければ、この演習全体はほとんど無意味です):
g.DoIt (l.begin(), l.end());
GCC は、テンプレート引数を推測できないと文句を言います。
prog.cpp: In function ‘int main()’:
prog.cpp:34:28: error: no matching function for call to ‘Gizmo<unsigned int>::DoIt(std::list<std::basic_string<char> >::iterator, std::list<std::basic_string<char> >::iterator)’
g.DoIt (l.begin(), l.end());
^
prog.cpp:34:28: note: candidate is:
prog.cpp:16:49: note: template<template<class> class typedef Cont Cont> void Gizmo<Foo>::DoIt(typename Cont<std::basic_string<char> >::const_iterator, typename Cont<std::basic_string<char> >::const_iterator) [with Cont = Cont; Foo = unsigned int]
template <template <typename> class Cont> void DoIt(
^
prog.cpp:16:49: note: template argument deduction/substitution failed:
prog.cpp:34:28: note: couldn't deduce template parameter ‘template<class> class typedef Cont Cont’
g.DoIt (l.begin(), l.end());
最終的に、私が本当に気にかけているDoIt
のは、コレクションの begin および end イテレータで呼び出せることだけですstring
。コレクションの実際のタイプはvector
またはlist
のいずれかであり、テンプレート引数を指定する必要も、コンテナーに基づいてオーバーロードする必要もありません。
どうすればこれを機能させることができますか?
私の実際のユースケースは C++03 であることに注意してください。C++11 ソリューションは歓迎されますが、C++03 ソリューションのみを受け入れることができます。