c++ - 使用指向成员的指针将成员函数作为参数传递

标签 c++ function-pointers pointer-to-member function-binding

#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::)()’ 

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

最佳答案

您不能传递非静态成员函数来执行,因为它依赖于 this 元素(因此它需要一个调用对象),您可以使用 lambda :

execute([&](){foo.print();});

关于c++ - 使用指向成员的指针将成员函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403304/

相关文章:

c - ansi c 全局可访问回调

c++ - 使用宏访问指向数据成员的指针会产生 "error: expected unqualified-id before ‘*’ token ”

c++ - 从音频文件转换ExtAudioFile时,ExtAudioFileGetProperty失败

c++ - 使用 opencv 和 c++ 找到最接近复杂形状的匹配项的最佳方法是什么?

c++ - GPSD 在 libgpsmm 中给出模式 0

c++ - 如何使用循环在 C++ 中打印指针

c++ - 如何定义采用相同参数类型五次的函数类型

c++ - 模板函数指针: "overloaded function with no contextual type information"

c++ - 将指针传递给静态方法

C++从指针调用成员函数在引入参数时调用内存访问冲突