typename

Started by
6 comments, last by svpace 21 years, 1 month ago
Hi, what means the c++ keyword typename? for instance why the compiler complains about not using it in template typedefs or what is the diference between template class A{}; and template class A{};. Sorry if I''m wrong but as far as I can tell it seens a little useless.
Advertisement
quote:Original post by svpace
Hi, what means the c++ keyword typename? for instance why the compiler complains about not using it in template typedefs or what is the diference between template class A{}; and template class A{};. Sorry if I''m wrong but as far as I can tell it seens a little useless.


The writer of my c++ book says that its the same.

There''s no difference. A lot of people feel that "typename" is clearer, since the datatype need not be a class. A lot of other people feel it doesn''t matter. Do whatever floats your boat.

Oh, and use code and source tags on the forums, or your template definitions will disappear.

But... but that''s what HITLER would say!!
Sorry by that. what I mean is what te diference between
  template<class T> class A{}; template<typename T> class A{};   

So, typename has no reason to exist?


[edited by - svpace on March 4, 2003 2:49:46 PM]
typename is also used to define types that do not yet exist.

example:


    template<class T> class X{   typename T::A var;};   


The class T is not known yet, but for this to compile correctly T must declare a type A. The 'typename' keyword tells the compiler to treat A as a type that will be defined in T. That allows you to create a variable 'var' as type T::A.

But in the case you mentioned:


        template<class T> class X {/*...*/};// andtemplate<typename T> class X {/*...*/};   


'class T' and 'typename T' have the same meaning.



[edited by - LodeRunner on March 4, 2003 3:07:56 PM]

[edited by - LodeRunner on March 4, 2003 3:09:21 PM]
There is no semantic difference between template<typename T> class A and template <class T> class A.

As for why it''s necessary inside templated code, consider the following:

  class SomeClass {  public:    typedef int my_type;    static my_type A;};int SomeClass::A;template <typename T>void func(typename T::my_type val) {  T::A = val;}void some_func(void) {  func<SomeClass>(5);}  


typename, in this case, is used to disambiguate between potential static variable references and type references. Basically it allows syntax to be checked during the template defintion rather than postponing it to instantiation, where the error messages will probably be much more cryptic.
Thank you all, I think I got the idea.
Coincidentally, there''s an article on this very topic in the latest issue of Dr. Dobbs.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man

This topic is closed to new replies.

Advertisement