I have a templated class with a method for which I need a different implementation for a specific template type. How do i get it done?
views:
155answers:
3
+4
A:
You'll have to create a partial (or full) specialization for this particular type.
Timo Geusch
2009-11-15 10:34:44
You’ve got to specialize the whole type though, you cannot just partially specialize member functions. This is implicit in the answer but it could be misunderstood.
Konrad Rudolph
2009-11-15 10:43:23
You can get around this limitation by using a base class to provide the default implementation (and making the constructors / destructors of this base class protected to avoid using it).
Matthieu M.
2009-11-15 14:40:33
+1
A:
You can specialise the method for that type. E.g.
template<typename T>
struct TemplatedClass
{
std::string methodA () {return "T methodA";}
std::string methodB () {return "T methodB";}
std::string methodC () {return "T methodC";}
};
// Specialise methodA for int.
template<>
std::string TemplatedClass<int>::methodA ()
{
return "int methodA";
}
jon hanson
2009-11-15 12:17:12
+2
A:
Timo's answer only allows you to specialize the class as a whole, meaning that the compiler won't automatically copy the member functions from the base type to the specialized type.
If you want to specialize a particular method in the class without re-creating everything else, it's a little more complicated. You can do it by passing a size-zero templated struct as an argument, like this:
template<typename T> struct TypeHolder { };
template<typename T> class TemplateBase {
public:
void methodInterface() {
methodImplementation(TypeHolder<T>);
}
void anotherMethod() {
// implementation for a function that does not
// need to be specialized
}
private:
void methodImplementation(TypeHolder<int>) {
// implementation for int type
}
void methodImplementation(TypeHolder<float>) {
// implementation for float type
}
};
The compiler will inline the appropriate methodImplementation
into methodInterface
, as well as elide the size-zero struct, so it will be just as if you had done a specialization on the member function only.
int3
2009-11-15 15:04:15