开发者

c++: call overloaded function for derived classes as arguments too (without explicit cast)

开发者 https://www.devze.com 2023-03-10 23:32 出处:网络
Imagine the following scenario: template<class T> void myFunction(T *) { //do nothing } void myFunction(myBase * _base)

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消