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

here is what I would like to do:

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

      

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

However, this does not compile (the callback does not know when parsing the argument, even if the compiler knows the size of arg, since it is const ref)

Does anyone know of some hack (with a template perhaps?) That is less ugly than the one I'm using:

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

      

This is "ugly" because I have to use arg.value and not arg directly.

NB: I need to use std :: function and not a C-Like pointer, preventing the use of void * and cast. Thanks to

Bean

+3


source to share


2 answers


You're right. The type is not known at this time because it has not yet been defined. It's just in the middle of the definition.

What you can try is inherit the new class from std::function<>

instead of flattening it. You will be able to reference the subclass name in the parent class template instance similar to CRTP and thanks to C ++ 11 you will be able to import all constructors in a simple string.



This one works :

#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;
}

      

+2


source


Here's what I have, which seems a little 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;
}

      

+1


source







All Articles