通常のテンプレート
通常のテンプレートはテンプレート パラメーターでオーバーロードしませんが、任意の多くのテンプレート パラメーターで部分的に特殊化できます。;
すべての構造体宣言/定義を後ろに置く限り、コードは機能するはずです。type
(テンプレート内のネストされた型を、値を として表すのが慣例であることに注意してくださいvalue
):
#include <iostream>
template<typename T>
struct FeatureType;
class Foo { };
template<> struct FeatureType<Foo>
{
typedef int type;
type value;
};
template<typename T> class Bar { };
template<typename T> struct FeatureType<Bar<T>>
{
typedef T type;
type value;
};
template<typename A, typename B> class Huh {};
template<typename A, typename B>
struct FeatureType< Huh<A,B> >
{
typedef A type;
type value;
};
int main()
{
FeatureType<Foo> f0;
f0.value = 0;
FeatureType< Bar<int> > f1;
f1.value = 1;
FeatureType< Huh<int, int> > f2;
f2.value = 2;
std::cout << f0.value << f1.value << f2.value;
}
LiveWorkSpaceでの出力(gcc 4.7.2)
注: 複数の正式なテンプレート パラメータ ( A
、B
、または好きなだけ) がある場合でも、実際のテンプレートは単一のクラスに部分的に特化されています。Huh<A, B>
可変個引数テンプレート
異なる数のテンプレート パラメーターを使用する複数のバージョンが実際にFeatureType
必要な場合は、可変個引数テンプレート (C++11) を使用する必要があります。
#include <iostream>
template<typename... Args>
struct FeatureType;
template<> struct FeatureType<int>
{
typedef int type;
type value;
};
template<typename T> struct FeatureType< T >
{
typedef T type;
type value;
};
template<typename A, typename B>
struct FeatureType< A, B >
{
typedef A type;
type value;
};
int main()
{
FeatureType< int > f0;
f0.value = 0;
FeatureType< int > f1;
f1.value = 1;
FeatureType< int, int > f2;
f2.value = 2;
std::cout << f0.value << f1.value << f2.value;
}
LiveWorkSpaceでの出力