我有一个函数,它带有一个指向函数的指针:
std::shared_ptr<MyObj> MyObj::Create(const std::function<std::shared_ptr<MyInterface>()>& my_func);
然后我有一个功能,如:
std::shared_ptr<MyInterface> MyQualifier::GetInterfaceInstance() {
return my_interface_instance;
}
但是当我尝试:
my_obj = MyObj::Create(&MyQualitifer::GetInterfaceInstance);
我收到一个错误:
Reference to type const std::function<std::shared_ptr<MyInterface> ()>' could not bind to an rvalue of type 'std::shared_ptr<MyInterface> (ParentQualifier::MyQualifier::*)()'
为什么是这样?
作为参考,我有一个类似的函数定义为:
std::shared_ptr<MyInterface> CreateMyInterface();
并且以下代码按预期工作:
my_obj = MyObj::Create(&CreateMyInterface);
正如@IgorTandetnik正确指出的那样,问题似乎出在该类的非静态成员函数上。
如果是非静态成员函数,this
则由编译器隐式添加。
这就是编译器抱怨的原因。因为该函数与中期望的类型不匹配std::shared_ptr<MyObj> MyObj::Create(const std::function<std::shared_ptr<MyInterface>()>& my_func);
。
解:
选项1)使其为静态。像这样:
class MyQualifier {
...
public:
static std::shared_ptr<MyInterface> MyQualifier::GetInterfaceInstance() {
return my_interface_instance;
}
}
...
auto my_obj = MyObj::Create(&MyQualitifer::GetInterfaceInstance); // now, this should work
请注意,在这种情况下,my_interface_instance
应为静态数据成员。
选项2)创建一个对象MyQualifier
并使用lambda。
int main() {
auto my_obj = MyObj::Create([]() {
auto myQualifierInstance = MyQualifier{};
return myQualifierInstance->GetInterfaceInstance();
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句