Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the typename keyword exist in C++, for backwards compatibility with “C templates?”

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?

like image 911
ELLIOTTCABLE Avatar asked Feb 25 '10 19:02

ELLIOTTCABLE


People also ask

Is typename a keyword in C?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.

What is use of typename keyword in C++?

Use the keyword typename if you have a qualified name that refers to a type and depends on a template parameter. Only use the keyword typename in template declarations and definitions.

Why is typename needed?

The typename keyword is needed whenever a type name depends on a template parameter, (so the compiler can 'know' the semantics of an identifier (type or value) without having a full symbol table at the first pass).


2 Answers

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.

like image 156
Brian R. Bondy Avatar answered Oct 16 '22 10:10

Brian R. Bondy


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.

like image 28
John Marshall Avatar answered Oct 16 '22 11:10

John Marshall