Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c++:也将派生类的重载函数作为参数调用(无显式强制转换)_C++_Casting_Overloading - Fatal编程技术网

c++:也将派生类的重载函数作为参数调用(无显式强制转换)

c++:也将派生类的重载函数作为参数调用(无显式强制转换),c++,casting,overloading,C++,Casting,Overloading,想象一下以下场景: template<class T> void myFunction(T *) { //do nothing } void myFunction(myBase * _base) { //do something with _base } int main( int argc, const char* argv[] ) { myDerivedFromBase * ptr =

想象一下以下场景:

    template<class T>
    void myFunction(T *)
    {
       //do nothing
    }

    void myFunction(myBase * _base)
    {
       //do something with _base
    }

int main( 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;
}

基本上,我希望实现为指针调用模板化函数,这些指针不是从我的基派生的。如果ptr是从myBase派生的,我希望调用myFunction的第二个版本时不使用显式强制转换。可能吗

使用类型特征防止模板绑定:

template<typename T>
typename std::enable_if<!std::is_base_of<myBase, T>::value, void>::type myFunction(T*)
{
}

如果不能使用C++0x,请改用Boost的类型特征库。

如果可以使用指向基的指针,请参见下文,您可以使用模板专门化: 包括 使用名称空间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;
}

这不会对运行时速度造成影响,因为它发生在编译时,对吗?是的,它完全是编译时的,它会阻止编译器匹配从myBase派生的类的模板。运行时不会发生任何额外的情况。好吧,我使用boost尝试了这个方法,但似乎无法让它工作。我得到以下错误:模板typename boost::enable_if::value,bool>::type myFuncT*_bla{coutYou需要使用boost::enable_if_c to作为我的原始版本的直接等价物。或者,使用boost也可以这样做:模板typename boost::disable_if::type myfunction*。区别在于boost::enable_if需要一个具有bool值成员的类型,而不是像c++0x的std::enable_if.boost::ena那样直接使用boolble_if_c是一个接受bool的类型。也许这会起作用:namespace std{template class enable_if:public boost::enable_if_c{};}?这只是使用隐式强制转换而不是显式强制转换。OP试图包含更多的情况,而不仅仅是精确匹配。