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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With