Search code examples
c++iterable-unpacking

Python-like Iterable Unpacking in C++


In python, we can unpack an iterable with a unary * like so:

def foo(a, b, c):
    ...

t = (1, 2, 3)
foo(*t)

In C++, I haven't encountered an equivalent. I'm aware that I could use structured bindings to solve a similar problem:

void foo(std::tuple<int, int, int> param)
{
    auto [a, b, c] = param;
    ...
}

But for the sake of curiosity, what if I wanted my function signature to accept three ints instead? Is there an elegant way of unpacking an iterator or a collection into the parameters of a function call?


Solution

  • For arrays you can use std::tuple_cat + std::apply like this: (Live demo)

    #include <array>
    #include <tuple>
    #include <utility>
    #include <iostream>
    #include <format>
    
    void f(int a,int b,int c)
    {
        std::cout << std::format("{}, {}, {}\n", a, b, c);
    }
    
    int main()
    {
        std::array<int,3> arguments{1,2,3};
        std::apply(f, std::tuple_cat(arguments));
    }
    

    Note, this only works if the size of the data is known at compile time.