Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么可以';我不能传递这个函数吗?C++;_C++ - Fatal编程技术网

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();
    });
}