There's a new syntax in C++11 for creating a type alias, using
. It can be used, where typedef
is used, and can be templated. The explanation which favors using
, goes like this:
It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:
template<class T> typedef std::vector<T,MyAllocator<T>> Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disadvantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector<*,MyAllocator<*>>
- where the asterisk is a placeholder for a type-name. Consequently, we do not propose the "typedef" syntax.template<class T> using Vec = std::vector<T,MyAllocator<T>>;
can be read/interpreted as: from now on, I'll be using
Vect<T>
as a synonym forstd::vector<T,MyAllocator<T>>
. With that reading, the new syntax for aliasing seems reasonably logical.
However, I don't get it. We use templates for classes, functions, and we don't have a separate keyword for them. Then why do we have a separate keyword for typedef
?
I.e.:
class Foo {
};
template <typename>
class Bar {
};
We use class
for both Foo
and Bar
, and Foo
is an actual class, but Bar
is a template, a "collection" of classes.
Can someone shed some light on this?