views:

432

answers:

6

I’m taking a C++ class, and my teacher mentioned in passing that the typename keyword existed in C++ (as opposed to using the class keyword in a template declaration), for backwards compatibility with “C templates.”

This blew my mind. I’ve never seen or heard tell of anything like C++’s templates (except, perhaps, the preprocessor… and that’s not really the same thing at all) in ANSI C. So, did I miss something huge somewhere, or is this a really esoteric extension by gcc or something, or is my teacher way off-base?

+20  A: 

I think your teacher is off base.

See Stan Lippman's post: Why C++ Supports both Class and Typename for Type Parameters for the real reason why C++ supports both.

Brian R. Bondy
Thanks a ton, that cleared it right up.
elliottcable
Great question by the way.
Brian R. Bondy
Thanks, man. It’s nearly pushed me over 100 reputation, *finally*! d-;
elliottcable
The Lippman post a is a good one for answering both this question and explaining why `typename` is sometimes needed in other contexts.
Michael Burr
A: 

This doesn't seem right. typename is not a reserved word at all in C.

Perhaps they misspoke/remembered and were thinking of "C with Classes".

jkerian
+1  A: 

No, there's no such thing as a C template. typename isn't even a keyword in C.

Joe Gauterin
+2  A: 

Your teacher is making things up. There's no such thing as templates in C. The typename keyword exists for two reasons:

  1. It makes more sense to say template<typename T> than template<class T> since T can be non-class types like int or double.

  2. It can be used to resolve parsing ambiguities in declarations like A::B * foo;. Does this declare a variable named foo, or is it a multiplication expression? (Answer: It's parsed as the latter. To make it a declaration write typename A::B *foo; which tells the compiler to interpret A::B as a type name, not a variable name.)

See http://pages.cs.wisc.edu/~driscoll/typename.html for a detailed explanation.

John Kugelman
A: 

Perhaps the phrase your teacher was aiming for was along the lines of "...for backwards compatibility with C types", i.e., recognizing the problem that template<class T> is misleading when T is a C-style built-in type such as char or int, as others have said. But that's not a class! :-)

A while back a few GCC folks were suggesting that making the template machinery available to the C compiler would be a good way to implement C99's <tgmath.h>, but that doesn't appear to have come to anything.

John Marshall