C ++ - use default template as a base for specialization

I want to write a mathematical vector template. I have a class that takes type and size as an argument to a template, with many methods of mathematical operation. Now I want to write specializations, where Vector <3>, for example, has x, y, z as elements that reference data [0..3], respectively.

The problem is that I donโ€™t know how to create a specialization that inherits everything from the default template without creating a base class or writing everything twice.

What is 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 }; 
+6
source share
2 answers

Somehow you should be able to extract from the default implementation, but you specialize in the instance, so how? it must be a non-specialized version that you can extract from it. So 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 }; 
+7
source

Think about it a little differently, but the goals will be achieved, add an external interface - I mean the stand-alone 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 not much difference between:

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

and

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

As a bonus, this interface works to fit the size.

+1
source

Source: https://habr.com/ru/post/927885/


All Articles