5

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.

Community
  • 1
  • 1
Samaursa
  • 16,527
  • 21
  • 89
  • 160
  • If nothing else, `Helper::type` is actually the right type. It's been a while since I've seriously dug into such things, but IIRC there are some subtle issues with type deduction and such. –  May 16 '12 at 15:56

3 Answers3

7

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.

Daniel
  • 30,896
  • 18
  • 85
  • 139
7

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.

Tadeusz Kopec for Ukraine
  • 12,283
  • 6
  • 56
  • 83
  • Sure, but we are creating new types anyway (every time the template arguments are different), so in the end, is there really a difference? – Samaursa May 16 '12 at 16:06
3

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")

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63