C++11 : typedef std::function and argument on itself

4.3k views Asked by At

here is what I would like to do:

typedef std::function<void(const callback&)> callback;

(Ie: defining a std::function that can pass as first arg an object of same type as itself).

However this doesn't compile (callback is not know when parsing argument, even if compiler knows the size of the arg as it's a const ref)

Does anyone knows some kind of hack (perhaps with template?) less ugly than the one I'm using:

struct scallback;
typedef std::function<void(const scallback&)> callback;
struct scallback { callback value; };

It's "ugly" because I have to use arg.value and not arg directly..

NB: I have to use std::function and not C-Like pointer, preventing using void* and cast. Thanks

Bob

2

There are 2 answers

1
Krizz On BEST ANSWER

You are right. The type is not known at this point as it has not been defined yet. It's just in the middle of being defined.

What you can try is to inherit a new class from std::function<> instead of type-aliasing it. You will be able to reference the subclass name in the parent class template instantiation similarly to CRTP and thanks to C++11 you will be able to import all constructors in a simple line.

This seems to work:

#include <functional>

struct callback : std::function<void(const callback&)> {
  using std::function<void(const callback&)>::function;
};

void test(const callback& cb) {}

int main() {
    callback cb = test;
    test(cb);
    return 0;
}
0
Bob On

Here is what I have which seems a bit better:

struct callback_arg;
typedef std::function<void(const callback_arg&)> callback;

struct callback_arg : callback // callback_arg can be seen as a callback
{
    // callback can be seen as a callback_arg
    callback_arg(const callback& a) : callback(a) 
    {
    };
};

void Foo(const callback& val) {};
void Fuu(const callback& val) {};

int main()
{
    callback foo = Foo;
    callback fuu = Fuu;

    foo(fuu); // compiles correctly

    return 0;
}