6

What is the difference between writing a template in c++ in the below both ways

template<typename T> & template<class T>

and when do we prefer them above each other? If both are same,then why do we have them both if one is enough?

Vijay
  • 65,327
  • 90
  • 227
  • 319
  • I prefer `typename` because my templates accept non-class types (but yes, they are exactly equivalent of course) โ€“ Cubbi Apr 25 '11 at 10:28
  • possible duplicate of [C++ difference of keywords 'typename' and 'class' in templates](http://stackoverflow.com/questions/2023977/c-difference-of-keywords-typename-and-class-in-templates) โ€“ Matt Nov 14 '11 at 11:22

2 Answers2

9

No difference at all. I prefer first one (mostly), but that is my personal taste. The language doesn't make any difference between them.

For template parameters, the keywords typename and class are equivalent. ยง14.1.2 says:

There is no semantic difference between class and typename in a template-parameter.


If both are same,then why do we have them both if one is enough?

Stan Lippman explains this in his article:

Why C++ Supports both Class and Typename for Type Parameters?

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • More information can be found [in this blogpost](http://blogs.msdn.com/b/slippman/archive/2004/08/11/212768.aspx). โ€“ orlp Apr 25 '11 at 09:54
3

These keywords are there because of historical reason. There's no difference between them. Read this: http://blogs.msdn.com/b/slippman/archive/2004/08/11/212768.aspx

Kien Truong
  • 11,179
  • 2
  • 30
  • 36