Variadic templates: unfold arguments in groups
You can accomplish it with overloads.
template <typename T1, typename T2>
void bar(T1&& arg1, T2&& arg2) {
foo( std::forward<T1>(arg1), std::forward<T2>(arg2) ); // (until) sends (the last) two arguments to foo
}
template <typename T1, typename T2, typename... Args>
void bar(T1&& arg1, T2&& arg2, Args&&... args) {
foo( std::forward<T1>(arg1), std::forward<T2>(arg2) ); // sends the 1st two arguments to foo
bar( std::forward<Args>(args)... ); // call bar with remaining elements recursively
}
LIVE
Note that with the minimum snippet above when calling bar
with 0 or odd arguments you'll get no matching function error. If you want more clear compilation message with static_assert
you can start from this snippet.
C++17 generalization for n
-ary functors:
namespace impl
{
template<std::size_t k, class Fn, class Tuple, std::size_t... js>
void unfold_nk(Fn fn, Tuple&& tuple, std::index_sequence<js...>) {
fn(std::get<k + js>(std::forward<Tuple>(tuple))...);
}
template<std::size_t n, class Fn, class Tuple, std::size_t... is>
void unfold_n(Fn fn, Tuple&& tuple, std::index_sequence<is...>) {
(unfold_nk<n * is>(fn, std::forward<Tuple>(tuple),
std::make_index_sequence<n>{}), ...);
}
}
template<std::size_t n, class Fn, typename... Args>
void unfold(Fn fn, Args&&... args) {
static_assert(sizeof...(Args) % n == 0);
impl::unfold_n<n>(fn, std::forward_as_tuple(std::forward<Args>(args)...),
std::make_index_sequence<sizeof...(Args) / n>{});
}
int main() {
auto fn = [](auto... args) {
(std::cout << ... << args) << ' ';
};
unfold<2>(fn, 1, 2, 3, 4, 5, 6); // Output: 12 34 56
unfold<3>(fn, 1, 2, 3, 4, 5, 6); // Output: 123 456
}
Simple recursion using if constexpr
:
// print as many pairs as we can
template<class T, class U, class... Args>
void foo(T t, U u, Args&&... args)
{
std::cout << t << " + " << u << "\n";
if constexpr(sizeof...(Args) > 0 && sizeof...(Args) % 2 == 0)
foo(std::forward<Args>(args)...);
}
template<class... Args>
void bar(Args&&... args)
{
static_assert(sizeof...(Args) % 2 == 0);
foo(std::forward<Args>(args)...);
}
Call it like so:
bar(1, 2, 3, 4);
Demo
I would say that songyanyao's answer is pretty canonical pre-C++17. Afterwards, if constexpr
has allowed us to move logic into the bodies of our functions instead of using overloading tricks.