将成员函数传递给另一个对象的成员函数C ++ [英] Passing member function to another object's member function C++

查看:186
本文介绍了将成员函数传递给另一个对象的成员函数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题试图传递一个函数作为参数在另一个对象的函数。我很清楚,有很多类似的主题,但我不能得到他们的解决方案工作或不能理解他们。

I am having issues trying to pass a function as an argument in another object's function. I am well aware there are many similar topics but I either can't get their solution to work or can't understand them.

class foo
{
public:
    void func1(void (*Drawing)(void));

    template<class T>
    void func2(void (T::*Drawing)(void));
};

class bar
{
private:
    foo myFoo;
    void Drawing();
    void func3() {
        // Attempt 1
        myFoo.func1(Drawing);

        // Attempt 2
        myFoo.func2<bar>(&bar::Drawing);
    }
};

所以在我第一次尝试,我得到的错误,你不能转换 void(bar :: *)(void) void(*)(void),然后发现有正常的函数指针和成员函数指针。

So in my first attempt, I get the error where you can't convert void (bar::*)(void) to void (*)(void) of which I then found out there are normal function pointers and member function pointers.

尝试2是我的微弱尝试克服这个,但我现在得到未解决的外部...

Attempt 2 was my feeble attempt to overcome this but I get unresolved externals now...

那么,如何成功地将 Drawing()成员函数传递给另一个对象的另一个函数?

So how can I successfully pass my Drawing() member function into another function from another object?

推荐答案

问题是你不能将 bar :: Drawing 视为 void(*)(void)函数,因为它是一个非静态方法,因此需要一个对象(上下文将被使用)

The issue is that you cannot consider bar::Drawing as a void (*)(void) function since it's a non static method, which therefore required an object (the this context which will be used)

一个解决方案,假设c ++ 11对你来说,就是使用 std :: bind ,并轻松地修改你的foo定义:

A solution, assuming c++11 is ok for you, would be to use std::bind and to sligtly modify your foo definition:

class foo
{
    public:
    void func1(std::function<void(void)> Drawing)
    {
        Drawing(); // or do whatever you want with it
    }
};

那么你将能够做

void bar::func3() {
    myFoo.func1(std::bind(&bar::Drawing, this));
}

使大量潜在用途有效

int main()
{
    bar myBar;
    myBar.func3();

    foo myFoo;
    myFoo.func1([](){ printf("test\n"); });
    return 0;
}

这篇关于将成员函数传递给另一个对象的成员函数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆