Archived

This topic is now archived and is closed to further replies.

svpace

typename

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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!!

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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 {/*...*/};
// and
template<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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites