具有不同类型参数的泛型类型的特性类实现
Traits class implementation for generic types with different type params
我有以下类特征
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)上的输出
注意:即使您有多个正式模板参数(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 上的输出
我不确定你到底尝试了什么,但你可以随心所欲地专门化模板参数:
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;
}
看看它在行动中。
相关文章:
- 使用泛型类型推送到堆栈时出现问题
- 为堆栈实现泛型集合
- 如何在容器中指定模板化别名的泛型类型
- 具有模板专用化的泛型类型转换
- C++存储泛型 T 类型类的向量
- 如何在C++中返回没有模板的泛型类型?
- 如何在带有约束 (C++) 的函数中使用泛型类型
- 模板函数重载(泛型类型与模板模板类型)选择正确的重载
- 泛型类型别名,它们彼此不兼容
- 泛型类型转换
- 重载泛型类型的模板类时检查运算符=时的自赋值
- 在C++中,如何根据类中的参数返回不同的泛型类型
- C++错误 C2227:'->looseHealth'左侧必须指向类/结构/联合/泛型类型
- 在C++中实现泛型向量类
- 使用泛型类型显式实例化函数模板
- 函数模板中的无效转换错误,返回值取决于其泛型类型
- 如何在非泛型类型上实现完美转发
- C++具有自定义类的泛型类型实现
- 使用C++生成泛型类型-一个具有共享实现的模板
- 具有不同类型参数的泛型类型的特性类实现