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 回答