Member function callback

#include <iostream>
#include <pthread.h>

class Core;

class Thread
{
public:
    Thread();
    virtual ~Thread();

protected:
    virtual void run() = 0;
private:
    static void* threadWrapper(void* me);
private:
    pthread_t mThread;
};

Thread::Thread()
{
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    pthread_create(&mThread, &attr, threadWrapper, this);

    pthread_attr_destroy(&attr);
}

void* Thread::threadWrapper(void* me)
{
    static_cast<Thread*>(me)->run();
    return NULL;
}

Thread::~Thread()
{
    void* dummy;
    pthread_join(mThread, &dummy);
}

class Q : public Thread //Event queue that can be timed
{
public:
    Q(Core* pb, void (Core::*method)()):
                m_pb(pb),m_method(method){}
    void show()
    {
        (m_pb->*m_method)();
    }
private:
    virtual void run()
    {
       for(;;)
       {
           sleep(1);std::cout << "running..." << std::endl;
       }
    }

private:
    Core* m_pb;
    void (Core::*m_method)();
};


class Core //The exellent core class which can be named with framework that handles and solves many complicated things
{
public:
    Core()
    {
        m_a = new Q(this, &Core::show);
    }
    void onSomeWorkDone() //Always be called by other
    {
        m_a->show();
    }
private:

    void show()
    {
        std::cout<<"Executing..."<<std::endl;
    }
private:
    Q* m_a;
};

int main()
{
    Core* c = new Core;
    //w->show();//Invalid, the Core::show() is private
    c->onSomeWorkDone();
    while(1)
    {
     sleep(20);
    }
}
在C++中,回调函数是一种常见的编程模式,用于将函数作为参数传递给另一个函数,并在适当的时候调用该函数。回调函数广泛应用于事件驱动编程、异步操作、定时器管理等场景。以下是C++中回调函数的几种常见实现方式及其使用方法。 ### 1. 使用函数指针实现回调 函数指针是最基础的回调实现方式。通过将函数地址作为参数传递给另一个函数,接收方可以在适当的时候调用该函数。 ```cpp #include <iostream> // 定义回调函数类型 typedef void (*Callback)(int); // 被调用的回调函数 void myCallback(int value) { std::cout << "Callback called with value: " << value << std::endl; } // 接收回调函数并调用 void registerCallback(Callback cb, int value) { if (cb) { cb(value); } } int main() { registerCallback(myCallback, 42); return 0; } ``` ### 2. 使用`std::function`和`std::bind`实现更灵活的回调 `std::function`是C++11引入的标准库类型,可以封装任何可调用对象(包括函数指针、lambda表达式、绑定表达式等),提供了更高的灵活性。 ```cpp #include <iostream> #include <functional> // 使用 std::function 封装回调 void registerCallback(const std::function<void(int)>& cb, int value) { if (cb) { cb(value); } } int main() { // 使用 lambda 表达式作为回调 registerCallback([](int value) { std::cout << "Lambda callback called with value: " << value << std::endl; }, 42); return 0; } ``` ### 3. 使用类成员函数作为回调 在面向对象编程中,有时需要将类的成员函数作为回调函数。由于成员函数具有隐含的`this`指针,因此需要使用`std::bind`或lambda表达式来绑定对象实例。 ```cpp #include <iostream> #include <functional> class MyClass { public: void callback(int value) { std::cout << "Member function callback called with value: " << value << std::endl; } }; void registerCallback(const std::function<void(int)>& cb, int value) { if (cb) { cb(value); } } int main() { MyClass obj; // 使用 std::bind 绑定成员函数和对象实例 registerCallback(std::bind(&MyClass::callback, &obj, std::placeholders::_1), 42); return 0; } ``` ### 4. 使用lambda表达式简化回调定义 lambda表达式提供了一种简洁的方式来定义匿名函数对象,常用于回调函数的实现,特别是在异步操作或事件处理中。 ```cpp #include <iostream> #include <functional> void registerCallback(const std::function<void(int)>& cb, int value) { if (cb) { cb(value); } } int main() { registerCallback([](int value) { std::cout << "Lambda callback called with value: " << value << std::endl; }, 42); return 0; } ``` ### 5. 回调与异步编程结合使用 在异步编程中,回调函数通常用于处理操作完成后的结果。例如,在网络请求或文件读取完成后触发回调。 ```cpp #include <iostream> #include <functional> #include <thread> #include <chrono> void asyncOperation(const std::function<void()>& cb) { std::thread([cb]() { std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "Async operation completed." << std::endl; if (cb) { cb(); } }).detach(); } int main() { asyncOperation([]() { std::cout << "Callback after async operation." << std::endl; }); std::cin.get(); // 防止主线程退出 return 0; } ``` ### 6. 使用回调处理定时器事件 在实时系统或操作系统中,定时器通常使用回调函数来处理到期事件。例如,µC/OS-II等嵌入式操作系统中,定时器的回调函数会在定时器到期时被调用[^3]。 ```cpp #include <iostream> #include <functional> #include <thread> #include <chrono> class Timer { public: using Callback = std::function<void()>; void start(int milliseconds, const Callback& cb) { std::thread([=]() { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); if (cb) { cb(); } }).detach(); } }; int main() { Timer timer; timer.start(1000, []() { std::cout << "Timer expired!" << std::endl; }); std::cin.get(); // 防止主线程退出 return 0; } ``` ### 7. 异常处理与回调 在使用回调函数时,需要注意异常处理。特别是在回调中抛出异常并重新抛出时,必须小心处理,否则可能导致程序崩溃或不可预测的行为[^4]。 ```cpp #include <iostream> #include <functional> #include <stdexcept> void safeCallback(const std::function<void()>& cb) { try { if (cb) { cb(); } } catch (const std::exception& e) { std::cerr << "Exception caught in callback: " << e.what() << std::endl; } } int main() { safeCallback([]() { throw std::runtime_error("Something went wrong!"); }); return 0; } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值