445

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?

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Notinlist
  • 16,144
  • 10
  • 57
  • 99

1 Answers1

662

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>.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 57
    Oh great, I hadn't seen this part of C++0x and I've been bitching about templated typedef for a while... guess I should have a more thorough read of the final draft. – Matthieu M. May 09 '10 at 11:19
  • 3
    Will inheriting constructors make the OP's original solution are more viable solution? – StackedCrooked Aug 24 '12 at 06:07
  • 3
    @StackedCrooked: Depends on his goals. I avoid inheritance when composition will do (and yeah, inheriting constructors will make both of these easier), but I also avoid composition when a typedef will do. – GManNickG Aug 24 '12 at 14:34
  • 3
    using does not support specialization if I'm not wrong, so the second option is still useful in many cases. – Utkarsh Bhardwaj Feb 03 '16 at 14:27
  • @UtkarshBhardwaj Notice you can combine the two, similar to the way that `` contains alias declarations such as `std::remove_reference_t` the refer to various specializations of `std:::remove_reference`. – Spencer May 05 '21 at 13:01