Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is template typedef an issue in C++ (not C++11)

In this question the OP asked for a solution to template typedef which is not possible in C++. The OP also presented a solution themselves but did not like it:

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

// Problem - will not compile
typedef Matrix<N,1> Vector<N>;

// Solution
template <int N>
class Vector: public Matrix<N,1>
{ };

My question is, what advantage does the Helper::type solution give us over the OP's solution (assuming these classes are never meant to be used by a base pointer or new'd as such)? An empty class should carry no overhead in release (or does it?). The only disadvantage I can see is that in debug builds you will have to expand the base class when debugging.

EDIT: In addition to the selected answer, see @Dani's answer who suggested that the inherited version would require constructors to be defined, which is an added inconvenience.

like image 635
Samaursa Avatar asked May 16 '12 15:05

Samaursa


3 Answers

The point of typedef is to define a type alias. A subclass is not a type alias - it is a new type.

For example, imagine some library function

template<size_t N, size_t M>
Matrix<N, M> * createMatrix();

Now with helper type

Vector<3>::type * var = createMatrix<3, 1>();

is legal.
With inheritance

Vector<3> * var = createMatrix<3, 1>();

is not.

like image 109
Tadeusz Kopec for Ukraine Avatar answered Oct 09 '22 17:10

Tadeusz Kopec for Ukraine


It's because constructors are not inherited (and in c++11 not by default). So you have to copy all the non default constructs, even if you simply call the base class constructor in the implementation.

like image 30
Dani Avatar answered Oct 09 '22 16:10

Dani


Apart everyone taste on the syntax (that may be subjective) the main difference is that, by inhetirance, vector is actually another type that decays into matrix, while using an helper containing a typedef, vector is an alias of matrix (at least for what the partial specialization applies).

The difference requires vector to redefine constructors (that are not inherited), or some potential pitfalls in case of operations defined in term of template specialization (with typedef, they will never be seen as "differnet")

like image 33
Emilio Garavaglia Avatar answered Oct 09 '22 17:10

Emilio Garavaglia