C++ template typedef

C++TemplatesC++11Typedef

C++ Problem Overview


I have a class

template<size_t N, size_t M>
class Matrix {
    // ....
};

I want to make a typedef which creates a Vector (column vector) which is equivalent to a Matrix with sizes N and 1. Something like that:

typedef Matrix<N,1> Vector<N>;

Which produces compile error. The following creates something similar, but not exactly what I want:

template <size_t N>
class Vector: public Matrix<N,1>
{ };

Is there a solution or a not too expensive workaround / best-practice for it?

C++ Solutions


Solution 1 - C++

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNotinlistView Question on Stackoverflow
Solution 1 - C++GManNickGView Answer on Stackoverflow