Re: typedef for template
Am 27.07.2011 01:49, schrieb Abhishek Padmanabh:
On 26-Jul-11 3:27 AM, Venkat S wrote:
Hi,
I've searched and not found any reference for this, so I thought
it's ok to post.
template<typename T> class Foo { ... };
template<typename X> class Bar {
typedef Foo<X> Foo; // is this a legal c++ construct?
Foo fooObj;
};
Considering the reuse of the symbol 'Foo', as a type-definition, was a
typo (which is quite reasonable since otherwise you could have stated
the problem without using templates), yes, you can do the above.
I don't think that the OP code was a typo, because the example would
still does only make sense, because the template parameter is used
within Bar.
In
fact, this is a well-known workaround for absence of template typedefs
support in C++ i.e. you can't do:
template <typename T>
class Foo {};
template <typename T>
typedef Foo<T> mytype; //error
Above looks pretty useless, but consider having more parameters to the
template and you wanting to create a type definition with only fewer
parameters. For example:
template <typename T, typename U>
class Foo {};
template <typename U>
typedef Foo<int, U> mytype; //error
You'd have to use a class like 'Bar' above to be able to create the
type-definition 'mytype'.
In C++0x you can realize above via an alias template like this:
template<typename U>
using mytype = Foo<int, U>;
It has exactly the same semantics like a typedef, i.e. it does not
define a new type, but just defines an alias family. In fact, the good
old typedef alias can now be written in the new style using the keyword
'using' instead of 'typedef' even in the absence of templates. Thus, the
usual
typedef X Y;
can be rewritten as
using Y = X;
for practically all cases.
HTH & Greetings from Bremen,
- Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]