传递函数对象指向函数的指针,接受指向std::函数的指针

passing function objects pointers to functions accepting a pointer to a std::function

本文关键字:指针 函数 std 对象 传递函数      更新时间:2023-10-16

我想传递不同类型但签名相同的函子给一个方法。因此我得出结论,应该使用std::函数。但是由于这个方法还应该存储对函数对象的引用,所以我想传递一个shared_ptr(用于生命周期管理)。下面的代码适用于类B (B .run(…)),但无法编译类A (A .run(…)中断)。当传递指针而不是函数对象本身时,这种转换问题的原因是什么?我如何绕过它?

#include <functional>
#include <memory>
class MyFunctor
{
public:
    void operator()(const float &f)
    {}
};
template<class FunSig>
class A
{
public:
    void run(std::shared_ptr<std::function<FunSig> > f_ptr)
    {
         // store f_ptr in a vector
    }
};
template<class FunSig>
class B
{
public:
    void run(std::function<FunSig> f)
    {}
};
int main()
{
    MyFunctor mf1;
    std::shared_ptr<MyFunctor> mf2_ptr(new MyFunctor);
    A<void (const float &)> a;
    B<void (const float &)> b;
    a.run(mf2_ptr);        // this breaks!
    b.run(mf1);            // this works
}

编译错误:

error: no matching function for call to ‘A<void(const float&)>::run(std::shared_ptr<MyFunctor>&)’
note: candidate is:
note: void A<FunSig>::run(std::shared_ptr<std::function<FunSig> >) [with FunSig = void(const float&)]
note:   no known conversion for argument 1 from ‘std::shared_ptr<MyFunctor>’ to ‘std::shared_ptr<std::function<void(const float&)> >

现在我发现a.run(…)编译如果MyFunctor继承自std::function:

class MyFunctor : public std::function<void (const float &)>

为什么现在可以工作?如果在函子中不需要修改代码,那就更好了。

你的问题相当于问为什么这不起作用:

struct Integer
{
    int value;
};
std::shared_ptr<int> p(new int(1));
std::shared_ptr<Integer> p2 = p;

这不起作用,因为它们不是同一类型。仅仅因为你可以将MyFunctor存储在std::function<void(const float&)>中,并不意味着指向一个的指针可以转换为指向另一个的指针。

你想:

auto mf2_ptr = std::make_shared<std::function<void (const float &)>>( MyFunctor() );
a.run(mf2_ptr);

现在我发现a.run(…)编译如果MyFunctor继承自std::function:

它可以编译,因为现在你可以将shared_ptr<MyFunctor>转换为shared_ptr<function<void(const float&)>>,但它不能正常工作。std::function::operator()()不是虚拟的,所以如果你调用这个函数,它将调用基类' operator(),但是基类不指向任何东西,并且会抛出std::bad_cast

我不太明白为什么要引用std::function对象。除非您真的想要共享引用语义(例如,让其他人能够修改正在使用的函数对象),否则只需直接存储std::function对象。