General equivalent with respect to the variational function
Was there some search and couldn't find an answer to this question, so I apologize if a rep. I want to call the same function with the same argument on a bunch of different objects. I currently have implemented it like 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 this is not a very tedious bit of code in and of itself, I'm just wondering if there was an easier or cleaner way to iterate over this parameter pack than this recursive call? Thank!
source to share
Here is the most concise way I know of to express it:
template<typename ...T>
void callWithArg(const char *msg, T &&...t) {
int dummy[] = { 0, (t.foo(msg), 0)... };
}
The package extension expands to a list of type expressions int
that are used to initialize the array dummy
(which we throw away). The call is foo
sequenced because in C ++ 11 the list initialization elements are ordered from left to right.
If you add #include <initializer_list>
, you can simplify this a bit:
auto dummy = { 0, (t.foo(msg), 0)... };
You can also disallow the unused variable warning that various compilers produce on this code, with
(void) dummy;
The original is 0,
included to avoid an error if no arguments other than msg
. I've also reordered your function parameters to put the package last so that the types in the package can be defined.
source to share