2
#include <iostream>
#include <functional>

class Foo 
{
    public:
    Foo(int value)
    : value_(value){}
    void print()
    {
        std::cout << "member print: " << value_ << std::endl;
    }
    int value_;
};

void print()
{
    std::cout << "stand alone print" << std::endl;
}

template<typename F>
void execute(F&& f)
{
    f();
}

int main()
{ 

    execute(print);

    Foo foo(5);

    auto binded = std::bind(&Foo::print,foo);
    execute(binded);

    //auto Foo::* foo_print = &Foo::print;
    //execute(foo.*foo_print);

}

上面的代码编译并运行良好。

但是,如果使用指向 print 成员函数的指针的最后一部分未注释,则编译失败并显示:

error: invalid use of non-static member function of type ‘void (Foo::)()’ 

代码中是否存在语法错误,或者由于某种原因这是不可能的?

4

1 回答 1

3

You can't pass a non-static member function to execute, because it depends on the this element (and so it needs an invocation object), instead you can use a lambda:

execute([&](){foo.print();});
于 2020-02-25T21:25:13.133 回答