79302575

Date: 2024-12-23 08:41:40
Score: 1
Natty:
Report link

I evolved the idea of @user3820843, added couple null checks and here's what I've got:

#include <iostream>

template<class CLASS>
class CallbackClass
{
    typedef void(CLASS::*PVoid)();
private:
    CLASS *p = nullptr;
    PVoid pCallback = nullptr;
public:
    CallbackClass() {}
    ~CallbackClass(){}

    bool set_callback(CLASS *c, PVoid f)
    {
        if (!(c && f))
            return false;
        p = c;
        pCallback = f;
        return true;
    }

    bool callback()
    {
        bool r = false;
        if (p && pCallback)
        {
            (p->*(this->pCallback))();
            r = true;
        }
        return r;
    }

};

class A
{
public:
    A()  {}
    ~A() {}
    CallbackClass<A> t;
    void this_callback()
    {
        std::cout << "Callback" << std::endl;
    }
};

int main()
{
    A *a = new A;

    std::cout << a->t.set_callback(a, &A::this_callback) << std::endl;
    
    std::cout << a->t.callback();
    
    return 0;
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @user3820843
  • Low reputation (1):
Posted by: alex