类型特征专业化

5 c++ templates

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;
Run Code Online (Sandbox Code Playgroud)

这是标量和向量的类型特征,唯一的区别是向量的标量类型是其元素的类型.工作良好.

但我真的希望能够为这两个类使用相同的名称.

template<typename T>
struct numeric_type_traits_c
{
    typedef T type_t;
    typedef ????? scalar_t;
};
Run Code Online (Sandbox Code Playgroud)

我知道如果类明确专门用于我需要的每种类型,这是可行的:int,float,vec3,vec3 ......

这有很多重复...我如何保持第一位代码的简单性,但同时具有相同的类名?

Mar*_*utz 5

这是部分类模板特化的语法:

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;
};
Run Code Online (Sandbox Code Playgroud)

等等,例如:

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;
};
Run Code Online (Sandbox Code Playgroud)