Skeen
Skeen

Reputation: 4722

Template template parameters, why is class forced?

The titlen pretty much says all, if I write;

                                        vvvvv
template <template <typename, typename> class StdContainer, typename T>
class DerivedContainer: public StdContainer<T, std::allocator<T>>
{ /*...*/ };

Why is the class keyword required? That is when typename is allowed, as a replacement in all other template contexts. Disambiguation? Also which part of the standard states this?

Note; I do not derive from std containers, this is just an example.

Upvotes: 3

Views: 288

Answers (2)

jrok
jrok

Reputation: 55395

The usage of keyword class when declaring template template parameters is mandated by the grammar:

n3337, §14.1 [temp.param]:

1 The syntax for template-parameters is:

template-parameter:

type-parameter
parameter-declaration

type-parameter:

class ...opt identifier opt
class identifier opt = type-id
typename ...opt identifier opt
typename identifier opt= type-id
template < template-parameter-list > class ...opt identifier opt
template < template-parameter-list > class identifier opt = id-expression

I don't know the exact reason for this. When you've got a simple type parameter, the type can be anything from fundamental types to user declared classes, specializations of class templates, etc. When it's a template template parameter, it can only be a name of class template. Maybe they wanted to emphasize this difference - or maybe they just didn't bother inserting few more lines in the grammar and adding to confusion. Who knows :)

Upvotes: 5

Mike Seymour
Mike Seymour

Reputation: 254451

class has two meanings: to declare a class (or class template), or to declare a template type parameter.

typename can be substituted for the second meaning, but not the first. In a template template parameter, you're declaring a class template, so you must use class.

Upvotes: 1

Related Questions