admin管理员组

文章数量:1296432

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?

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?

Share Improve this question asked Feb 11 at 22:46 OctaOcta 1197 bronze badges 5
  • I'm unaware of any way to do this in C++. – Rud48 Commented Feb 11 at 23:28
  • @user4581301 I'm okay with deleting the comments. The duplicate answer still doesn't work. The OP is trying to expand a struct to fill the three arguments without changing the function. – Rud48 Commented Feb 12 at 2:07
  • Compiled, strictly-typed language. You wouldn't be able to that without pre-described adaptor and only at compile time. Before C++23 std::apply, such adaptor, doesn't come at zero cost. – Swift - Friday Pie Commented Feb 12 at 5:18
  • @Rud48 What was the duplicate answer that was linked? I'd be interested in reading it. – Octa Commented Feb 12 at 18:58
  • 1 @Octa Sorry, I don't recall – Rud48 Commented Feb 12 at 19:30
Add a comment  | 

1 Answer 1

Reset to default 5

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.

本文标签: Pythonlike Iterable Unpacking in CStack Overflow