传递函数对象指向函数的指针,接受指向std::函数的指针
passing function objects pointers to functions accepting a pointer to a std::function
我想传递不同类型但签名相同的函子给一个方法。因此我得出结论,应该使用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对象。
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址