kcc__
kcc__

Reputation: 1648

Difference between Class and Typename for C++ template

I am slightly confused about c++ template.

Considering the template below

template<class TYPE>
void function(TYPE data)

and

template<typename TYPE>
void function(TYPE data)

My confusion is exactly what is the difference between typename and class used as variable identify or type.

Upvotes: 5

Views: 7081

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477070

For designating (type) template parameters, the two are exactly identical, just like int/signed int, or &&/and: template <typename>/template <class>.

A curious restriction applies to template template parameters up to C++14:

template <template <typename> class Tmpl> struct Foo;
//                            ^^^^^

Here only the keyword class is allowed to designate the template template parameter.

After C++14, you will be able to consistently use either class or typename everywhere:

template <template <typename> typename Tmpl> struct Foo;

Upvotes: 13

Yochai Timmer
Yochai Timmer

Reputation: 49251

There IS a difference between the two.

class defines a class, so if you want to define a templated class as a template parameter, you have to use that.

For example you can define a template that receives a templated class type:

template <class A>
class Blah
{

};

template <template <class , class> class T, class A, class B>
class Blah<T<A,B>>
{

};

int _tmain(int argc, _TCHAR* argv[])
{
    Blah<std::vector<int>> a;

    return 0;
}

You can't declare a templated class like that with typename.

Also typename is used as a keyword to access dependent template names.

Upvotes: 3

Related Questions