简体   繁体   中英

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?

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.

Perhaps the phrase your teacher was aiming for was along the lines of "...for backwards compatibility with C types ", ie, 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.

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.

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

I wish to say that C really don't have a native template stuff, however, you can make it works fine with some kind of a MetaProgramming , take a look around the web you will find how to...

Another important thing to say is that C is a programming language to general purpose, so a lot of things like Object Orientation, template and some other things can be done with a little more effort.

Projects like Gnome are proof that it can be done and very well.

PS: Sorry about my terrible english!!!

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM