Wednesday, 15 April 2015

c++ - Foreach equivalent on variadic function -



c++ - Foreach equivalent on variadic function -

this question has reply here:

how create generic computations on heterogeneous argument packs of variadic template function? 5 answers

did searching , couldn't find reply question apologies if repost. want phone call same function same arg on bunch of different objects. implemented this:

void callwitharg(const char* msg) { } template <typename head, typename.... tail> void callwitharg(head&& head, tail&&... tail, const char* msg) { head.foo(msg); callwitharg(tail..., msg); }

obviously in not particularly tedious bit of code, wondering if there simpler or cleaner way of iterating on parameter pack kind of recursive invocation? thanks!

here's concise way know express this:

template<typename ...t> void callwitharg(const char *msg, t &&...t) { int dummy[] = { 0, (t.foo(msg), 0)... }; }

the pack expansion expands list of expressions of type int, used initialize array dummy (which throw away). calls foo sequenced, because in c++11, elements of list-initialization sequenced left-to-right.

if add together #include <initializer_list>, can simplify to:

auto dummy = { 0, (t.foo(msg), 0)... };

you may want suppress "unused variable" warning various compilers produce on code, with

(void) dummy;

the initial 0, included avoid error if function given no arguments other msg. reordered function's parameters set pack last, types in pack can deduced.

c++ c++11 variadic-functions

No comments:

Post a Comment