The problem
Say you have a generic matrix class like this with non-type template parameters for the number of rows and columns:
template <typename ElementType, size_t Rows, size_t Columns> class Matrix { ElementType entries_[Rows][Columns]; // etc... };
You would like to create a specialization for a column vector, where the number of columns is always 1. However, the following typedef
doesn’t compile:
typedef Matrix<size_t, Rows, 1> ColumnVector;
C++03
In C++03, you have 2 options.
Firstly, you can use inheritance:
template <typename ElementType, size_t Rows> class ColumnVector : public Matrix<ElementType, Rows, 1> { };
Secondly, you could use a class with a nested typedef
:
template <typename ElementType, size_t Rows> struct ColumnVector { typedef Matrix<ElementType, Rows, 1> type; };
In this case, you could declare a column vector with:
ColumnVector<int, 3>::type vec;
C++11
In C++11, you can use an alias declaration to solve the problem more neatly:
template <typename ElementType, size_t Rows> using ColumnVector = Matrix<ElementType, Rows, 1>;
This is a good example of how much more powerful the new alias declarations with using
are than typedef
s.