Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am writing callbacks system. I would to have something like that:

void someFunction(int, int);
void otherFunction(int, bool, std::string);
CallbackFunc *callback1 = new CallbackFunc( someFunction );
CallbackFunc *callback2 = new CallbackFunc( otherFunction );
callback1-> call(2, 6);
callback1-> call(1024, 456);
callback2-> call(-33, true, "Hello world");

My classes should can call each given function: don't know parameters count and their types. I was trying that:

class Callback {
public:
    virtual void call(...) = 0;
};

class CallbackFunc: public Callback {
protected:
    void (*m_proc)(...);
public:
    CallbackFunc(void (*proc) (...)) {
        this-> m_proc = proc;
    }
    void call (...) {
        this-> m_proc(<arguments given to call>);
    }
};

But it doesn't work. I have second idea:

template<typename ArgType>
class Arg {
protected:
    ArgType va;
public:
    Arg() {
    }
    Arg(ArgType v) {
        this->va = v;
    }
    ArgType get() {
        return this->va;
    }
    void operator =(ArgType v) {
        this->va = v;
    }
};


class Callback {
public:
    virtual void call(Arg, ...) = 0;
};

class CallbackFunc: public Callback {
protected:
    void (*m_proc)(Arg ...);
public:
    CallbackFunc(void (*proc) (Arg ...)) {
        this-> m_proc = proc;
    }
    void call (Arg arg...) {
        va_list args;
        va_start(args, arg);
        this-> m_proc(args);
        va_end(args);
    }
};

Still errors. Is it possible to make this way? I want to make usable code - user shouldn't know if CallbackFunc uses templates. I can't use void* and boost. C++ 2011 is not supported completely by some compilers I use, so that I can't use this standard too.

share|improve this question
2  
This is not possible in standard C++. –  n.m. Oct 19 '14 at 13:41
1  
You could recreate boost::function and then overload call with different numbers of template parameters. –  chris Oct 19 '14 at 13:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.