How can I use polymorphism with std::function?

时光怂恿深爱的人放手 提交于 2019-12-05 11:58:57

OK, well i've just done a workaround in the end.
The compiler won't let you downcast implicitly, so I've binded a cast method.
So, to keep it all generic and templated, it goes like this:

First, a helper class to get the function argument type:

template <typename T>
class GetFunctionArgumentVal;

template <class T, typename U >
class GetFunctionArgumentVal<std::function<U(T)>>
{
public:
    typedef T arg;
    typedef U returnVal;
};

Then, a cast operator that casts using static_cast (keeps compile time type safety), then calls the function with the derived class:

template <typename FUNCTION, typename BASE>
void castAndCall(FUNCTION bf, BASE& temp) 
{
    bf(static_cast< GetFunctionArgumentVal<FUNCTION>::arg >(temp));
}

Usage example:

class A {};

class B : public A {};

class C : public A {};

void targetB(B& temp) 
{

}

void targetC(C& temp) 
{

}

    std::function<void(A &)> af;
    std::function<void(B &)> bf = targetB;
    std::function<void(C &)> cf = targetC;

    B b;
    C c;

    af = std::bind(castAndCall<decltype(bf),A>,bf,std::placeholders::_1);
    af(b);

    af = std::bind(castAndCall<decltype(cf),A>,cf,std::placeholders::_1);
    af(c);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!