I was just messing about, when I discovered this pre-processor dependent way of creating a template class:
#include <iostream>
#include <typeinfo>
// Is this a valid template class?
#define TEMPLATE_CLASS(T)\
class TemplateClass_ ## T\
{\
private:\
T value;\
public:\
void print_type()\
{\
std::cout << typeid(T).name() << std::endl;\
}\
}
class Sample {};
TEMPLATE_CLASS(int) obj1;
TEMPLATE_CLASS(char) obj2;
TEMPLATE_CLASS(Sample) obj3;
int main(int argc, char* argv[])
{
obj1.print_type();
obj2.print_type();
obj3.print_type();
}
I compiled this simply with:
g++ src.cpp -o main.exe
The output:
i
c
6Sample
Now, as you can see, it pretty much works the same way as template classes. Except for the obvious fact than the objects can only be declared globally, since it actually defines a new class inline when you use TEMPLATE_CLASS(T)
, and new classes cannot be defined within a function. A solution to this can be:
TEMPLATE_CLASS(float);
int main() { TemplateClass_float obj; }
Anyway, this gave me a lot to think about. Firstly, can this even be called a valid generic class? And so, can it possibly be used instead of the standard template feature? Obviously, using the standard template feature is a lot more convenient, but what I mean to say is, will this work just as well? Lastly, does the template feature defined by the C++ standard internally do something similar to what I'm doing with the pre-processor? If not, what are the differences between this implementation and C++'s standard template feature?
It does the same thing as a template only in the simplest cases. Try doing this with macros: