2

I want to have a few functions in C++ where each function represents a screen in the program. The functions handle user interaction, and based on that will return a std::function to one of the other functions, with parameters bound via std::bind so that the return value can be called with no arguments. It is possible to get from any function to any other function by this process, without using recursion - the main function would be an infinite loop that just calls the returned function over and over.

But I'm stumped here - what should the definition of the return type be for these functions? They need to return std::function objects that take no parameters, but that's as far as I can get. std::function<what_goes_here ()>?

LB--
  • 2,506
  • 1
  • 38
  • 76
  • seems like object oriented job here, return an object and not a function.. – David Haim Aug 30 '15 at 12:55
  • I'm not exactly sure what you mean. If you want to return a function that takes no parameters, you can set the return value of that function to be `std::function`. With that return value, you could even return a lambda or a callable object (functor). http://coliru.stacked-crooked.com/a/198f2262449df1ca – LLLL Aug 30 '15 at 13:02

1 Answers1

4

C++ doesn't have any function type that directly or indirectly includes itself. You need some way to avoid the recursion in the type definition.

One way of doing that is by not returning a function. Instead, return a struct containing a function. Self-contained example with function pointers:

struct wrapper { wrapper (*function)(); };

wrapper f1();
wrapper f2();

wrapper f1() { return {f2}; }

The same approach also works with std::function.

  • Is `{f2}` a `std::initializer_list` object? Does this mean this will implicitly call the constructor of `wrapper`? But why not just `return f2`, I think this will also be implicitly converted to `wrapper`. – Allanqunzi Aug 30 '15 at 23:12
  • @Allanqunzi It's an initialiser list, which despite the name is not a `std::initializer_list` object. It uses aggregate initialisation, not an implicit conversion. If you try `return f2;` you should see a compiler error. –  Aug 31 '15 at 05:46