具有不同类型参数的泛型类型的特性类实现

Traits class implementation for generic types with different type params

本文关键字:实现 泛型类型 类型参数      更新时间:2023-10-16

我有以下类特征

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;
};

谢谢!

常规模板

常规模板不会重载其模板参数,但您可以将它们部分专用于任意多个模板参数。只要将;放在每个结构声明/定义后面,代码就应该可以工作。(注意,将模板内的嵌套类型表示为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 上的输出

我不确定你到底尝试了什么,但你可以随心所欲地专门化模板参数:

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;
}

看看它在行动中。