Reputation: 18108
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?
Upvotes: 19
Views: 11002
Reputation: 1
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!!!
Upvotes: 0
Reputation: 7005
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.
Upvotes: 6
Reputation: 362157
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>
than template<class T>
since T
can be non-class types like int
or double
.
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.
Upvotes: 3
Reputation: 13192
No, there's no such thing as a C template. typename
isn't even a keyword in C.
Upvotes: 2
Reputation: 17056
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".
Upvotes: 0
Reputation: 347586
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.
Upvotes: 26