template<typename T>
class vec3
{
public:
typename T type_t;
T x;
T y;
T z;
};
template<typename T>
struct numeric_type_traits_basic_c
{
typedef T type_t;
typedef T scalar_t;
};
template<typename T>
struct numeric_type_traits_vec3_c
{
typedef T type_t;
typedef typename T::type_t scalar_t;
};
typedef numeric_type_traits_basic_c<int> int_type_traits;
typedef numeric_type_traits_vec3_c< vec3<int> > vec3_int_type_traits;
这是标量和 vector 的类型特征,唯一的区别是 vector 的标量类型是其元素的类型。工作正常。
但我真的很希望能够为这两个类使用相同的名称。
template<typename T>
struct numeric_type_traits_c
{
typedef T type_t;
typedef ????? scalar_t;
};
我知道如果该类明确专门用于我需要的每种类型,那么这样做是可能的:int、float、vec3、vec3...
这是很多重复...我怎样才能保持第一段代码的简单性,同时具有相同的类名?
最佳答案
这是分部类模板特化的语法:
template<typename T>
struct numeric_type_traits // basic template
{
typedef T type_t;
typedef T scalar_t;
};
template<typename T>
struct numeric_type_traits< vec3<T> > // partial specialisation for vec3's
{
typedef vec3<T> type_t;
typedef T scalar_t;
};
等等,例如:
template <typename T, typename T_Alloc>
struct numeric_type_traits< std::vector<T,T_Alloc> > // part. spec. for std::vector
{
typedef std::vector<T,T_Alloc> type_t; // deal with custom allocators, too
typedef T scalar_t;
};
关于c++ - 类型特征特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1108682/