pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

使用類成員的 C++ 回調(diào)

C++ callback using class member(使用類成員的 C++ 回調(diào))
本文介紹了使用類成員的 C++ 回調(diào)的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!

問(wèn)題描述

我知道這個(gè)問(wèn)題已經(jīng)被問(wèn)過(guò)很多次了,正因?yàn)槿绱耍液茈y深入挖掘這些問(wèn)題并找到一個(gè)簡(jiǎn)單的例子來(lái)說(shuō)明什么是有效的.

I know this has been asked so many times, and because of that it's difficult to dig through the cruft and find a simple example of what works.

我知道了,它很簡(jiǎn)單,適用于 MyClass...

I've got this, it's simple and it works for MyClass...

#include <iostream>
using std::cout;
using std::endl;

class MyClass
{
    public:
        MyClass();
        static void Callback(MyClass* instance, int x);
    private:
        int private_x;
};

class EventHandler
{
    public:
        void addHandler(MyClass* owner)
        {
            cout << "Handler added..." << endl;
            //Let's pretend an event just occured
            owner->Callback(owner,1);
        }
};

EventHandler* handler;

MyClass::MyClass()
{
    private_x = 5;
    handler->addHandler(this);
}

void MyClass::Callback(MyClass* instance, int x)
{
    cout << x + instance->private_x << endl;
}

int main(int argc, char** argv)
{
    handler = new EventHandler();
    MyClass* myClass = new MyClass();
}

class YourClass
{
    public:
        YourClass();
        static void Callback(YourClass* instance, int x);
};

如何重寫(xiě),以便 EventHandler::addHandler() 可以與 MyClassYourClass 一起使用.我很抱歉,但這只是我大腦的工作方式,我需要先看看一個(gè)簡(jiǎn)單的例子,然后才能理解它為什么/如何工作.如果您有最喜歡的方法來(lái)完成這項(xiàng)工作,現(xiàn)在是時(shí)候展示它了,請(qǐng)標(biāo)記該代碼并將其發(fā)回.

How can that be rewritten so EventHandler::addHandler() will work with both MyClass and YourClass. I'm sorry but it's just the way my brain works, I need to see a simple example of what works before I can comprehend why/how it works. If you've got a favorite way to make this work now's the time to show it off, please markup that code and post it back.

有人回答了,但在我打勾之前答案就被刪除了.就我而言,答案是模板化函數(shù).將 addHandler 更改為此...

It was answered but the answer was deleted before I could give the checkmark. The answer in my case was a templated function. Changed addHandler to this...

class EventHandler
{
    public:
        template<typename T>
        void addHandler(T* owner)
        {
            cout << "Handler added..." << endl;
            //Let's pretend an event just occured
            owner->Callback(owner,1);
        }
};

推薦答案

您可以使用新的 C++11 標(biāo)準(zhǔn)中的功能,而不是使用靜態(tài)方法和傳遞指向類實(shí)例的指針:std::functionstd::bind:

Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: std::function and std::bind:

#include <functional>
class EventHandler
{
    public:
        void addHandler(std::function<void(int)> callback)
        {
            cout << "Handler added..." << endl;
            // Let's pretend an event just occured
            callback(1);
        }
};

addHandler 方法現(xiàn)在接受一個(gè) std::function 參數(shù),并且這個(gè)函數(shù)對(duì)象"沒(méi)有返回值并且接受一個(gè)整數(shù)作為參數(shù).

The addHandler method now accepts a std::function argument, and this "function object" have no return value and takes an integer as argument.

要將其綁定到特定函數(shù),請(qǐng)使用 std::bind:

To bind it to a specific function, you use std::bind:

class MyClass
{
    public:
        MyClass();

        // Note: No longer marked `static`, and only takes the actual argument
        void Callback(int x);
    private:
        int private_x;
};

MyClass::MyClass()
{
    using namespace std::placeholders; // for `_1`

    private_x = 5;
    handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}

void MyClass::Callback(int x)
{
    // No longer needs an explicit `instance` argument,
    // as `this` is set up properly
    cout << x + private_x << endl;
}

您需要在添加處理程序時(shí)使用 std::bind,因?yàn)槟枰鞔_指定其他隱式的 this 指針作為參數(shù).如果你有一個(gè)獨(dú)立的函數(shù),你就不必使用 std::bind:

You need to use std::bind when adding the handler, as you explicitly needs to specify the otherwise implicit this pointer as an argument. If you have a free-standing function, you don't have to use std::bind:

void freeStandingCallback(int x)
{
    // ...
}

int main()
{
    // ...
    handler->addHandler(freeStandingCallback);
}

讓事件處理程序使用 std::function 對(duì)象,還可以使用新的 C++11 lambda 函數(shù):

Having the event handler use std::function objects, also makes it possible to use the new C++11 lambda functions:

handler->addHandler([](int x) { std::cout << "x is " << x << '
'; });

這篇關(guān)于使用類成員的 C++ 回調(diào)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How can I read and manipulate CSV file data in C++?(如何在 C++ 中讀取和操作 CSV 文件數(shù)據(jù)?)
In C++ why can#39;t I write a for() loop like this: for( int i = 1, double i2 = 0; (在 C++ 中,為什么我不能像這樣編寫(xiě) for() 循環(huán): for( int i = 1, double i2 = 0;)
How does OpenMP handle nested loops?(OpenMP 如何處理嵌套循環(huán)?)
Reusing thread in loop c++(在循環(huán) C++ 中重用線程)
Precise thread sleep needed. Max 1ms error(需要精確的線程睡眠.最大 1ms 誤差)
Is there ever a need for a quot;do {...} while ( )quot; loop?(是否需要“do {...} while ()?環(huán)形?)
主站蜘蛛池模板: 电车线(用于供电给电车的输电线路)-百科 | 螺旋叶片_螺旋叶片成型机_绞龙叶片_莱州源泽机械制造有限公司 | 量子管通环-自清洗过滤器-全自动反冲洗过滤器-沼河浸过滤器 | 空压机网_《压缩机》杂志| 玉米深加工设备|玉米加工机械|玉米加工设备|玉米深加工机械-河南成立粮油机械有限公司 | 没斑啦-专业的祛斑美白嫩肤知识网站-去斑经验分享 | 对辊式破碎机-对辊制砂机-双辊-双齿辊破碎机-巩义市裕顺机械制造有限公司 | 高压互感器,电流互感器,电压互感器-上海鄂互电气科技有限公司 | 等离子空气净化器_医用空气消毒机_空气净化消毒机_中央家用新风系统厂家_利安达官网 | 政府园区专业委托招商平台_助力企业选址项目快速落地_东方龙商务集团 | 铸钢件厂家-铸钢齿轮-减速机厂家-淄博凯振机械有限公司 | TPM咨询,精益生产管理,5S,6S现场管理培训_华谋咨询公司 | 美国HASKEL增压泵-伊莱科elettrotec流量开关-上海方未机械设备有限公司 | 自清洗过滤器,浅层砂过滤器,叠片过滤器厂家-新乡市宇清净化 | 玖容气动液压设备有限公司-气液增压缸_压力机_增压机_铆接机_增压器 | 煤矿支护网片_矿用勾花菱形网_缝管式_管缝式锚杆-邯郸市永年区志涛工矿配件有限公司 | 实验室装修_实验室设计_实验室规划设计- 上海广建净化工程公司 | 亳州网络公司 - 亳州网站制作 - 亳州网站建设 - 亳州易天科技 | 酒瓶_酒杯_玻璃瓶生产厂家_徐州明政玻璃制品有限公司 | 企业微信营销_企业微信服务商_私域流量运营_艾客SCRM官网 | 聚丙烯酰胺PAM-聚合氯化铝PAC-絮凝剂-河南博旭环保科技有限公司 巨野电机维修-水泵维修-巨野县飞宇机电维修有限公司 | 东莞市海宝机械有限公司-不锈钢分选机-硅胶橡胶-生活垃圾-涡电流-静电-金属-矿石分选机 | 对辊破碎机-液压双辊式,强力双齿辊,四辊破碎机价格_巩义市金联机械设备生产厂家 | 武汉高低温试验机-现货恒温恒湿试验箱-高低温湿热交变箱价格-湖北高天试验设备 | 361°官方网站| 焊接烟尘净化器__焊烟除尘设备_打磨工作台_喷漆废气治理设备 -催化燃烧设备 _天津路博蓝天环保科技有限公司 | 温州食堂承包 - 温州市尚膳餐饮管理有限公司 | 铝箔-铝板-花纹铝板-铝型材-铝棒管-上海百亚金属材料有限公司 | 广州展览制作工厂—[优简]直营展台制作工厂_展会搭建资质齐全 | 浙江红酒库-冰雕库-气调库-茶叶库安装-医药疫苗冷库-食品物流恒温恒湿车间-杭州领顺实业有限公司 | 高压绝缘垫-红色配电房绝缘垫-绿色高压绝缘地毯-上海苏海电气 | 天然鹅卵石滤料厂家-锰砂滤料-石英砂滤料-巩义东枫净水 | 北京银联移动POS机办理_收银POS机_智能pos机_刷卡机_收银系统_个人POS机-谷骐科技【官网】 | 青岛空压机,青岛空压机维修/保养,青岛空压机销售/出租公司,青岛空压机厂家电话 | 天津仓库出租网-天津电商仓库-天津云仓一件代发-【博程云仓】 | 低浓度恒温恒湿称量系统,强光光照培养箱-上海三腾仪器有限公司 | 纯化水设备-纯水设备-超纯水设备-[大鹏水处理]纯水设备一站式服务商-东莞市大鹏水处理科技有限公司 | 清管器,管道清管器,聚氨酯发泡球,清管球 - 承德嘉拓设备 | 多米诺-多米诺世界纪录团队-多米诺世界-多米诺团队培训-多米诺公关活动-多米诺创意广告-多米诺大型表演-多米诺专业赛事 | 煤矿支护网片_矿用勾花菱形网_缝管式_管缝式锚杆-邯郸市永年区志涛工矿配件有限公司 | 非标压力容器_碳钢储罐_不锈钢_搪玻璃反应釜厂家-山东首丰智能环保装备有限公司 |