Alias ​​pattern

I have a problem that I recently ran into. I actually think that it is impossible to solve as we would like, but it would be very convenient if it were possible. Anyway, here is the problem:

I will give you an example that I saw a few days ago in this forum, since it will be easier to explain with it. Let's say I'm trying to create a tensor structure like this:

template <int N> struct Tensor { Tensor<N - 1> x; Tensor<N - 1> y; Tensor<N - 1> z; }; 

To avoid infinite recursion, I would have to write a template specialization for N = 1.

 template<> struct Tensor<1> { double x; double y; double z; }; 

In fact, when N = 1, this Tensor is actually a Vector (physical). Say I already have a vector structure defined as follows:

 struct Vector { double x; double y; double z; }; 

This structure is exactly like Tensor <1>. Since the Vector structure already exists and, say, I did not implement it myself, I would like to be able to make the Tensor <1> structure an alias of the Vector structure. Same as typedef. So, I would like to do it as follows:

 // C++03 typedef Vector Tensor<1>; // or C++11 using Tensor<1> = Vector; 

Thus, Tensor <1 and Vector will be the exact structure, so I could use one instead of the other in the program, wherever I wanted, and I would not have to write the same structure twice.

However, it is actually not possible to define template specialization in this way. If that were the case, I would not ask a question there.

Note: I know that the previous example is not very good, since we can still do this:

 using Vector = Tensor<1>; 

But this is very annoying if I want to do this using the specializations of two different structures. For example, when writing a geometry library that could calculate geometry in N-dimensional spaces:

 using Circle<2> = Hypersphere<2>; 

So to summarize: is there a way to create specialized templates by defining it as an alias of another?

+6
source share
1 answer

Given the obsolete classes Scalar, Vector and Matrix, you can use inheritance:

 template<> class Tensor<0>: public Scalar {}; template<> class Tensor<1>: public Vector {}; template<> class Tensor<2>: public Matrix {}; 

Note that this is not an abuse of inheritance because you are modeling is-a relationships.

+8
source

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


All Articles