Question:
have a base class with a virtual function:
class Base
{
public:
virtual void Function();
};
void Base::Function()
{
cout << "default version" << endl;
}
and a derived template class:
template <class T> class Derived : public Base
{
public:
virtual void Function();
};
If want to have a way to make Function()
be taken from the base class for all types, except some chosen ones?
Solution1: (using type-id operator)
#include <iostream> #include <typeinfo> using namespace std; class Base { public: virtual void Function(); }; void Base::Function(){ cout<<"default version"<<endl; } template<typename T> //using template keyword for type branches class Derived : Base //from Base class { public: virtual void Function(); }; template<typename T> //using template keyword for type branches void Derived<T>::Function() { if(typeid(T) == typeid(int)) // check if T is an int { cout << "overriden version 1\n"; } else if(typeid(T) == typeid(long)) // check if T is a long int { cout << "overriden version 2\n"; } else // if T is neither an int nor a long { Base::Function(); // call default version } } int main() { Derived<int> di; Derived<long> dl; Derived<float> df; di.Function(); dl.Function(); df.Function(); return 0; }
同时用template specilization也可以解决这个问题