std :: function作为类之间的方法参数

时间:2019-02-10 17:20:49

标签: c++ class c++17

当我将方法名称传递给其他类方法时,它显示此错误:

$ g++ test.cpp -std=c++17
test.cpp: In member function ‘void Test::finish()’:
test.cpp:18:38: error: invalid use of non-static member function ‘bool 
Test::local_method(std::__cxx11::string)’
         t.add_method(local_method);
                                  ^
test.cpp:16:14: note: declared here
     bool local_method(string msg) {}

test.cpp

#include <functional>
#include <string>

using namespace std;

class Main {
    public:
        void add_method(function<bool(string)> fn) {
            // ...
        }
};
Main t;

class Test {
    public:
        bool local_method(string msg) {}
        void finish() {
            t.add_method(local_method);
        }
};

int min() {
    Test a;
    a.finish();
}

当我不使用类时,它可以在其他代码中工作:

void call(int a, function<int(int)> x) {
    cout << "--->>>" << x(a) << endl;
}
int give_an_int(int a) {
    return a * 123;
}
call(11, give_an_int);

0 个答案:

没有答案