Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Use default template as base for specialization

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
};
like image 210
weltensturm Avatar asked Oct 16 '12 21:10

weltensturm


2 Answers

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
};
like image 153
BigBoss Avatar answered Oct 11 '22 21:10

BigBoss


Consider making this in a little different way, but goals will be achieved, Add external interface - I mean standalone functions X(), Y(), Z():

template<class T, size_t S>
T& x(Vector<T, S>& obj, typename std::enable_if<(S>=1)>::type* = nullptr)
{
   return obj.data[0];
}

template<class T, size_t S>
T& y(Vector<T, S>& obj, typename std::enable_if<(S>=2)>::type* = nullptr)
{
   return obj.data[1];
}

template<class T, size_t S>
T& z(Vector<T, S>& obj, typename std::enable_if<(S>=3)>::type* = nullptr)
{
   return obj.data[2];
}

There is no big difference between:

 Vector<T, 3>& obj
 return obj.x();

And

 Vector<T, 3>& obj
 return x(obj);

As a bonus - this interface works for matching sizes.

like image 30
PiotrNycz Avatar answered Oct 11 '22 20:10

PiotrNycz