3

I want to achieve code looking similar to that

using ProcessCallback = std::function<ProcessCallback (const std::vector<char>&)>

// ...

ProcessCallback callback;
// initialize callback somehow...

while (/* condition */)    {
    auto callback_successor = callback (data);
    if (callback_successor)   {
       callback = std::move (callback_successor);
    }
}

In general I want to have callable callback object (function pointer, whatever) that will process some data and has possibly of replacing itself for successive calls.

The error is obvious - quasi-recursive declaration in first line is invalid, because I try to declare std::function<>-based type using undeclared ProcessCallback.

How can I fix aforementioned code or how can I achieve desired functionality with other construction? Abstract functional class for processing it's not the solution - I don't want to write new class inheriting from the abstract class for each processing function.

I want to stick to pure C++ (no Boos etc.), but I'm not limited to specific C++ version.

Edit

Actually I managed to workaround the problem, but I'm curious whether it;s possible to make initial solution working.

Goofy
  • 5,187
  • 5
  • 40
  • 56
  • `void*` would definitely be an option, but then you might have to turn away from std::function and start working with function pointers. – Sebastian Hoffmann Feb 29 '16 at 21:00
  • @SebastianHoffmann sure, but it's a "ugly" C hack I want to avoid - that's one of reasons of using C++ ;) – Goofy Feb 29 '16 at 21:02
  • What's the reason you don't just return a function pointer? – Weak to Enuma Elish Feb 29 '16 at 21:03
  • @JamesRoot because it will restrict functionality - I will not be able to e.g. return std::bind<> from processing functions. – Goofy Feb 29 '16 at 21:08
  • Isn't `using` just syntactic sugar? If you can't write something without `using` then you won't be able to make magic happen with a recursive `using`. – wally Feb 29 '16 at 21:10
  • 3
    Something like this? http://stackoverflow.com/q/23737449/2069064 – Barry Feb 29 '16 at 21:25

1 Answers1

0

The easiest approach that springs to my mind is using a class that provides the functionality you want. As an example:

struct Callback{
    std::function<void(void)> func;
    Callback* next = nullptr;

    Callback* call(){
        func();
        return next;
    }
};

It is somewhat like a linked list, containing the function to call and a pointer to the next element. Of course it could also (conditionally) just return this and/or modify func to change its own behaviour without pointing to a different object. call() could also be operator()() here for even easier syntax.

Use is quite simple, by defining a pointer to Callback and then call

ptr = ptr->call();

Try it online

Anedar
  • 4,235
  • 1
  • 23
  • 41