指向成员函数的c ++指针,替代__closure [英] c++ pointer to member function, replacement for __closure

查看:113
本文介绍了指向成员函数的c ++指针,替代__closure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前一段时间,Borland在其BCB环境中引入了对C ++语言的扩展.此扩展名是__closure关键字.问题是,是否有可能在纯C ++或C ++ 11中实现这种功能?如果您不熟悉__closure关键字,则下面的代码将在注释中提供解释.

Some time ago, Borland have introduced in their BCB evironment an extension to C++ language. This extension is a __closure keyword. The question is, if it is possible to implement such functionality in plain C++ or C++11? If you are not familiar with __closure keyword, below code provides explanation in comments.

提前谢谢! 都灵(Toreno)

Thanks in advance! Toreno

#include <stdio.h>

// __closure keyword is used here !
typedef void (__closure * MemberCallback)(int x, int y, int z);

class A
{
    private:

        MemberCallback callback;


    public:

        A() : callback(NULL)
        {
        }

        void setCallback(MemberCallback newCallback)
        {
            callback = newCallback;
        }

        void call(int x, int y, int z)
        {
            if(callback)
                callback(x, y, z);
            else
                printf("NOT SET(%i, %i, %i)\n", x, y, z);
        }
};

class B
{
    public:

        void func1(int x, int y, int z)
        {
            printf("FUNC 1(%i, %i, %i)\n", x, y, z);
        }

        void func2(int x, int y, int z)
        {
            printf("FUNC 2(%i, %i, %i)\n", x, y, z);
        }

};

int main()
{
    // A and B classes do not know about each other. There is no possibility
    // to for inheritance because B class can implement multiple instances
    // of callback function
    A a;
    B b;

    a.call(1, 2, 3);  // Prints: NOT SET(1, 2, 3)

    a.setCallback(b.func1);
    a.call(4, 5, 6);  // Prints: FUNC 1(4, 5, 6)

    a.setCallback(b.func2);
    a.call(7, 8, 9);  // Prints: FUNC 2(7, 8, 9)

    return 0;
}

推荐答案

std: :function 正是您想要的.如果您想了解库中实际上是如何实现这种机制的,请 lambda函数结合以捕获局部变量.

std::function is exactly what you're looking for. If you want to learn how such mechanism is actually implemented in the library, here's a good series of blog posts on it. Combine that with lambda functions for capturing of local variables.

这篇关于指向成员函数的c ++指针,替代__closure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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