Does the typename keyword exist in C++, for backwards compatibility with “C templates?”
I’m taking a C++ class, 开发者_Python百科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", 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.
No, ANSI C does not support templates.
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/com.ibm.xlcpp8a.doc/language/ref/keyword_typename.htm
Your teacher is making things up. There's no such thing as templates in C. The typename
keyword exists for two reasons:
It makes more sense to say
template<typename T>
thantemplate<class T>
sinceT
can be non-class types likeint
ordouble
.It can be used to resolve parsing ambiguities in declarations like
A::B * foo;
. Does this declare a variable namedfoo
, or is it a multiplication expression? (Answer: It's parsed as the latter. To make it a declaration writetypename A::B *foo;
which tells the compiler to interpretA::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.
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".
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.
P.S.: Sorry about my terrible english!!!
精彩评论