C++ - Use default template as base for specialization

c++, specialization, templates

Solution

Somehow you should be able to derive from default implementation, but you are specializing an instance, so how? it should be a non-specialized version that you can be able to derive from it. So that's simple:

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

Problem

I want to write a math vector template. I have a class which accepts type and size as template argument, with a lot of math operation methods. Now I want to write specializations where Vector<3> for instance has x, y, z as members which refer to data[0..3] respectively. The problem is that I don't know how to create a specialization which inherits everything from the default template without creating either a base class or writing everything twice. What's the most efficient way to do this? ``` 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 }; ```

Original source