@9月
「シンプルな」ソリューション
「sep」が投稿した回答は非常に優れており、おそらく 99% のアプリ開発者にとっては十分ですが、ライブラリ インターフェイスの一部である場合は、いくつかの改善が必要になる可能性があります。
ベクトルに特化するには:
template<typename C> void mySuperTempalte (std::vector<C> myCont)
{
//check type of container
//do something here
}
これは、呼び出し元が std::vector を使用していない場合に機能します。ベクトル、リストなどに特化するためにこれが十分に機能する場合は、ここで終了してそれを使用してください。
より完全なソリューション
まず、関数テンプレートを部分的に特化することはできないことに注意してください。オーバーロードを作成できます。それらの 2 つ以上が同程度に一致すると、「あいまいなオーバーロード」エラーが発生します。そのため、サポートするすべてのケースで正確に 1 つの一致を作成する必要があります。
これを行うための 1 つの手法は、enable_if 手法を使用することです。enable_if を使用すると、あいまいな言語ルールを使用して、可能な一致リストから関数テンプレートのオーバーロードを選択的に取り出すことができます...基本的に、ブール式が false の場合、オーバーロードは「見えなくなります」 . 興味がある場合は、SFINAE で詳細を調べてください。
例。このコードは、エラーなしで MinGW (g++ parameterize.cpp) または VC9 (cl /EHsc parameterize.cpp) を使用してコマンド ラインからコンパイルできます。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
template <bool B, class T> struct enable_if {};
template <class T> struct enable_if<true, T> { typedef T type; };
template <class T, class U> struct is_same { enum { value = false }; };
template <class T> struct is_same<T,T> { enum { value = true }; };
namespace detail{
// our special function, not for strings
// use ... to make it the least-prefered overload
template <class Container>
void SpecialFunction_(const Container& c, ...){
cout << "invoked SpecialFunction() default\n";
}
// our special function, first overload:
template <class Container>
// enable only if it is a container of mutable strings
typename enable_if<
is_same<typename Container::value_type, string>::value,
void
>::type
SpecialFunction_(const Container& c, void*){
cout << "invoked SpecialFunction() for strings\n";
}
}
// wrapper function
template <class Container>
void SpecialFunction(const Container& c){
detail::SpecialFunction_(c, 0);
}
int main(){
vector<int> vi;
cout << "calling with vector<int>\n";
SpecialFunction(vi);
vector<string> vs;
cout << "\ncalling with vector<string>\n";
SpecialFunction(vs);
}
出力:
d:\scratch>parameterize.exe calling
with vector<int> invoked
SpecialFunction() default
calling with vector<string> invoked
SpecialFunction() for strings
d:\scratch>