How should I call all functions in the package of variational parameters if the type of the returned function is invalid?

I have a package of parameters full of standard constructive and then called objects (for example, ExampleFunctor ), and you want to call them all in order (from left to right). If the return type is something other than void, I can use a list of initializers for this:

 struct ExampleFunctor{ void operator()(){someGlobal = 4;} }; template<typename... Ts> struct CallThem { void operator()(){ auto list = {Ts()()...}; } } 

however, if the return type is invalid, this trick does not work.

I could wrap all Ts in a wrapper that returns an int, but that seems redundant, and this code will eventually run on the M3 crust with 32K of flash memory, so the extra overhead of the wrapper function is a pain if I compile in mode debugging (and debugging in release mode makes my brain hurt).

Is there a better way?

+3
source share
3 answers

Using the comma operator:

 int someGlobal; struct ExampleFunctor{ void operator()(){someGlobal = 4;} }; template<typename... Ts> struct CallThem { void operator()(){ int list[] = {(Ts()(),0)...}; (void)list; } }; int main() { CallThem<ExampleFunctor, ExampleFunctor>{}(); } 

Btw I am not using initializer_list here, but just an array; try for yourself which one can be thrown by the compiler. (void)list is a warning (unused variable).

+6
source

The compiler should be able to optimize function calls here:

 template <typename H, typename... Tail> void call(H head, Tail... tail) { head(); call(tail...); } template <typename T> void call(T fn) { fn(); } template <typename... Args> void callThem() { call(Args()...); } 

But this is untested. Check the generated assembly for your platform.

+1
source

You can use something like:

 template<typename... Ts> struct CallThem; template<> struct CallThem<> { void operator()() const {} }; template<typename Tail, typename... Queue> struct CallThem<Tail, Queue...> { void operator()() const { Tail()(); CallThem<Queue...>()(); } }; 
0
source

Source: https://habr.com/ru/post/1247038/


All Articles