I'm very surprised to find that the following compiles:
#include <iostream>
using namespace std;
template<typename T>
class SomeCls {
public:
void UseT(T t) {
cout << "UseT" << endl;
}
};
template<>
class SomeCls<int> {
// No UseT? WTF?!??!?!
};
int main(int argc, char * argv[]) {
SomeCls<double> d;
SomeCls<int> i;
d.UseT(3.14);
// Uncommenting the next line makes this program uncompilable.
// i.UseT(100);
return 0;
}
Why is this allowed? It just seems wrong that class SomeCls<int>
doesn't need to have a void UseT(T t)
method. I'm sure I'm missing the point of specialization here (I'm not a C++ expert). Can someone please enlighten me?
It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Template Specialization (C++)A template has multiple types and only some of them need to be specialized. The result is a template parameterized on the remaining types. A template has only one type, but a specialization is needed for pointer, reference, pointer to member, or function pointer types.
Because SomeCls<double>
is a completely different type than SomeCls<int>
or any other SomeCls<T>
. They are not related in any way, so they can have whatever members they want. Just be sure not to call i.UseT()
, this is where the compiler would start to complain, of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With