C++ 为什么可以';我不能传递这个函数吗?C++;
我有一个函数,它接受指向函数的指针:C++ 为什么可以';我不能传递这个函数吗?C++;,c++,C++,我有一个函数,它接受指向函数的指针: std::shared_ptr<MyObj> MyObj::Create(const std::function<std::shared_ptr<MyInterface>()>& my_func); 我得到一个错误: Reference to type const std::function<std::shared_ptr<MyInterface> ()>' could not bind
std::shared_ptr<MyObj> MyObj::Create(const std::function<std::shared_ptr<MyInterface>()>& my_func);
我得到一个错误:
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\u ptr MyObj::Create(const std::function&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
MyQualifier::GetInterfaceInstance
实际上是一个使用一个参数的函数-MyQualifier*
(在函数体中由this
关键字表示)。它需要调用MyQualifier
的实例。这就是为什么它不能转换为std::function
——后者可以在没有参数的情况下调用。这个问题的答案是。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);
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
int main() {
auto my_obj = MyObj::Create([]() {
auto myQualifierInstance = MyQualifier{};
return myQualifierInstance->GetInterfaceInstance();
});
}