I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so.
-edit-
I’ll have several classes that inherit from SomeTag. I don’t want to write the same specialization for each of them.
class SomeTag {}; class InheritSomeTag : public SomeTag {}; template <class T, class Tag=T> struct MyClass { }; template <class T> struct MyClass<T, SomeTag> { typedef int isSpecialized; }; int main() { MyClass<SomeTag>::isSpecialized test1; //ok MyClass<InheritSomeTag>::isSpecialized test2; //how do i make this specialized w/o changing main() return 0; }
This article describes a neat trick: http://www.gotw.ca/publications/mxc++-item-4.htm
Here’s the basic idea. You first need an IsDerivedFrom class (this provides runtime and compile-time checking):
Then your MyClass needs an implementation that’s potentially specialized:
and MyClass actually looks like:
Then your main will be fine the way it is: