Imagine the following scenario:
template<class T>
void myFunction(T *)
{
//do nothing
}
void myFunction(myBase * _base)
{
//do something with _base
}
int main( 开发者_C百科int argc, const char* argv[] )
{
myDerivedFromBase * ptr = new myDerivedFromBase;
myFunction(ptr); //calls the templated version
myFunction(static_cast<myBase*>(ptr)); //calls the correct version
delete ptr;
}
basically I want to achieve that the templated function gets called for pointers, that are not derived from my base. If a ptr is derived from myBase I want that the second version of myFunction gets called without the explicit cast. Is that possible?
Use type traits to prevent the template from binding:
template<typename T>
typename std::enable_if<!std::is_base_of<myBase, T>::value, void>::type myFunction(T*)
{
}
If you can't use C++0x, use Boost's type traits library instead.
If you can use a pointer to base (see below), you can use template specialization: #include using namespace std;
class myBase {};
class myDerivedFromBase: public myBase {};
template<class T>
void myFunction(T *)
{
cout << "Most general function." << endl;
}
template<>
void myFunction(myBase * _base)
{
cout << "Specialized for myBase." << endl;
}
int main( int argc, const char* argv[] )
{
myDerivedFromBase * ptr = new myDerivedFromBase;
myFunction(ptr);
delete ptr;
myBase* bptr = new myBase;
myFunction(bptr);
delete bptr;
bptr = new myDerivedFromBase;
myFunction(bptr);
delete bptr;
}
精彩评论