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 int
s 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 int
s instead? Is there an elegant way of unpacking an iterator or a collection into the parameters of a function call?
- 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
1 Answer
Reset to default 5For 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
版权声明:本文标题:Python-like Iterable Unpacking in C++ - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741630185a2389315.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论