我有一个接受函数指针的函数:
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();
});
}
关于c++ - 为什么我不能通过这个功能? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56070147/