I use:
template<class T>
Arbol<T>::Arbol(){
}
when T
you are going to do a class.
and use:
template<typename T>
Arbol<T>::Arbol(){
}
when it is going T
to be a type, for example bool
, that is, char
fundamental types.
But looking at a code fragment of a program (not created by me) I saw that it used typename
where I usually use class
, and until now I had not noticed that. if now you ask me why, well, I wouldn't be able to say one hundred percent why, but perhaps somehow I (imagine) that the compiler differentiated when it was a type included in the language and acted accordingly.
My question is:
Is it the same to use one or the other?
Well, now I've tested both of them and they work fine, but I don't know if I'm missing something, or maybe there's some subtle difference between class
and typename
in this context.
In this context, It is the same , there is no difference.
They can be used interchangeably and exist for historical reasons.
In this blog post by Stan Lippman, he explains that Stroustrup initially didn't want to introduce a new keyword and reused
class
. Until the ISO-C++ standard it was the only way to declare it.During the standardization process, it was discovered that this caused syntactic ambiguities (see in the blog) and it was decided to introduce a new keyword to solve it. this is
typename
. It was finally overloadedclass
to work astypename
to maintain backwards compatibility.Regarding the use of
typename
orclass
to declare the type-parameter of a template, in most cases using one or the other of the keywords is indifferent, but there are certain cases in which it is required to use one or the other.For example, using is required
class
for the type of a template-parameter ( but this could change in C++17 ) and using is requiredtypename
to help the compiler distinguish between a type or a value (when the type is dependent).Excerpt from Paper n4051 (the translation is mine):
In short, for the vast majority of cases
class
ortypename
is indifferent, buttypename
it is the only option to disambiguate dependent types andclass
is required for the template-parameter type; they are the only two cases where both keywords are not interchangeable, but they are not the most common uses.When declaring a
template
simple it is indifferent to useclass
ortypename
. Both are exactly identical. However, for certain uses we will not have as much freedom of choice.If we need to make use of a type provided by the class/struct used to specialize the
template
we will have to redeclare the type in ourtemplate
. In this case we will have to usetypename
:If one of the types of the
template
turns out to be anothertemplate
(for example a container) we will have to useclass
if we want thetemplate
compile: