Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template typedef

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?

like image 681
Notinlist Avatar asked May 08 '10 17:05

Notinlist


People also ask

What is a typedef in C?

typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.

What is the difference between using and typedef?

Definition on C++ using vs typedef. In C++, 'using' and 'typedef' performs the same task of declaring the type alias. There is no major difference between the two. 'Using' in C++ is considered to define the type synonyms.

What is alias template?

This declaration may appear in block scope, class scope, or namespace scope. 2) An alias template is a template which, when specialized, is equivalent to the result of substituting the template arguments of the alias template for the template parameters in the type-id.

What is Typename C++?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.


1 Answers

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

like image 181
GManNickG Avatar answered Sep 29 '22 18:09

GManNickG