Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are structs not allowed in template definitions?

Tags:

c++

templates

The following code yields an error error: ‘struct Foo’ is not a valid type for a template constant parameter:

template <struct Foo>
struct Bar {

};

Why is that so?

template <class Foo>
struct Bar {

};

works perfectly fine and even accepts an struct as argument.

like image 623
nils Avatar asked Dec 02 '22 06:12

nils


1 Answers

This is just an artifact of the syntax rules - the syntax just lets you use the class or typename keywords to indicate a type template parameter. Otherwise the parameter has to be a 'non-type' template parameter (basically an integral, pointer or reference type).

I suppose Stroustrup (and whoever else he might have taken input from) decided that there was no need to include struct as a a keyword to indicate a type template parameter since there was no need for backwards compatibility with C.

In fact, my recollection (I'll have to do some book readin' when I get back home) is that when typename was added to indicate a template type parameter, Stroustrup would have liked to take away using the class keyword for that purpose (since it was confusing), but there was too much code that relied on it.


Edit:

Turns out the story is more like (from a blog entry by Stan Lippman):

The reason for the two keywords is historical. In the original template specification, Stroustrup reused the existing class keyword to specify a type parameter rather than introduce a new keyword that might of course break existing programs. It wasn't that a new keyword wasn't considered -- just that it wasn't considered necessary given its potential disruption. And up until the ISO-C++ standard, this was the only way to declare a type parameter.

Reuses of existing keywords seems to always sow confusion. What we found is that beginners were [wondering] whether the use of the class constrained or limited the type arguments a user could specify to be class types rather than, say, a built-in or pointer type. So, there was some feeling that not having introduced a new keyword was a mistake.

During standardization, certain constructs were discovered within a template definition that resolved to expressions although they were meant to indicate declarations

...

The committee decided that a new keyword was just the ticket to get the compiler off its unfortunate obsession with expressions. The new keyword was the self-describing typename.

...

Since the keyword was on the payroll, heck, why not fix the confusion caused by the original decision to reuse the class keyword. Of course, given the extensive body of existing code and books and articles and talks and postings using the class keyword, they chose to also retain support for that use of the keyword as well. So that's why you have both.

like image 176
Michael Burr Avatar answered Dec 04 '22 12:12

Michael Burr