C++ - 使用默认模板作为专业化的基础

wel*_*urm 6 c++ templates specialization

我想写一个数学矢量模板.我有一个接受类型和大小作为模板参数的类,有很多数学运算方法.现在我想编写专门化,其中Vector <3>例如x,y,z作为成员分别引用数据[0..3].

问题是我不知道如何创建一个从默认模板继承所有内容的特化,而无需创建基类或编写所有内容两次.

最有效的方法是什么?

template<class Type, size_t Size>
class Vector {
    // stuff
};

template<class T>
class Vector<3,T>: public Vector {
    public:
        T &x, &y, &z;
        Vector(): Vector<>(), x(data[0]), y(data[1]), z(data[2]){}
        // and so on
};
Run Code Online (Sandbox Code Playgroud)

Big*_*oss 7

不知何故,你应该能够从默认实现派生,但你是专门的实例,那么如何?它应该是一个非专业版本,您可以从中派生出来.这很简单:

// Add one extra argument to keep non-specialized version!
template<class Type, size_t Size, bool Temp = true>
class Vector {
    // stuff
};
// And now our specialized version derive from non-specialized version!
template<class T>
class Vector<T, 3, true>: public Vector<T, 3, false> {
    public:
        T &x, &y, &z;
        Vector(): Vector<>(), x(data[0]), y(data[1]), z(data[2]){}
        // and so on
};
Run Code Online (Sandbox Code Playgroud)