我想将不同类型的函子传递给一个方法。因此我认为应该使用std :: function。但是,由于此方法还应存储对函数对象的引用,所以我想要传递shared_ptr(用于生命周期管理)。下面的代码适用于B类(b.run(...)),但无法编译为A类(a.run(...)break)。 当传递一个指针而不是函数对象本身时,这个转换问题的原因是什么,我该如何绕过它?将函数对象指针传递给接受指向std :: function的函数的指针
#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从性病::功能继承:
class MyFunctor : public std::function<void (const float &)>
为什么这在工作,在忙?如果在函子中没有必要更改代码,我会更好。
这里的问题是一个类型转换。 MyFunctor *是指向MyFunctor结构的指针,std :: function *是指向std :: function对象的指针:当MyFunctor从std :: function继承时,代码会编译,因为它现在是一个子类std :: function,因此可以隐式转换。 –
IdeaHat
2013-04-09 16:23:02