1

私は次の特性クラスを持っています

template<typename T> struct FeatureType;

私はそれを次のように使用しています。

class Foo { };
template<> struct FeatureType<Foo> {
  typedef int value;
};

template<typename T> class Bar { };
template<typename T> struct FeatureType<Bar<T>> {
  typedef T value;
};

ジェネリック型のこの実装を、複数の型パラメーターを持つものに拡張する方法はありますか (Bar上記とは異なります)? 以下は動作しません

template<typename A, typename B> class Huh { };
template<typename A, typename B> struct FeatureType<Huh<A,B>> {
  typedef A value;
};

ありがとう!

4

2 に答える 2

1

通常のテンプレート

通常のテンプレートはテンプレート パラメーターでオーバーロードしませんが、任意の多くのテンプレート パラメーターで部分的に特殊化できます。;すべての構造体宣言/定義を後ろに置く限り、コードは機能するはずです。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)

: 複数の正式なテンプレート パラメータ ( AB、または好きなだけ) がある場合でも、実際のテンプレートは単一のクラスに部分的に特化されています。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での出力

于 2013-02-05T11:50:07.783 に答える
0

何を試したかは正確にはわかりませんが、必要な数のテンプレート引数を使用して専門化することができます。

template <typename A, typename B>
class foo { };

template <typename T>
struct feature_type {};

template <typename A, typename B>
struct feature_type<foo<A,B>> {
  typedef A type1;
  typedef A type2;
};

int main(int argc, const char* argv[])
{
  typename feature_type<foo<int,char>>::type1 x;
  typename feature_type<foo<int,char>>::type2 y;
  return 0;
}

実際の動作をご覧ください

于 2013-02-05T11:58:03.807 に答える