如何使用数字索引转换 varadic std::tuple 的所有元素? [英] How do I transform all elements of a varadic std::tuple using numerical indices?
问题描述
目前,我有一个这样的实现,以便使用一个函数 bar()
来转换元组的所有值,该函数接受元组的每个元素.
Currently, I have an implementation like this in order to transform all values of a tuple using a function bar()
that takes in each element of the tuple.
template<typename ... Args>
void foo(const std::tuple<Args...>& a)
{
std::tuple<Args...> transformedTuple = std::make_tuple(bar(std::get<Args>(a))...);
}
这样做的问题是,如果 Args
包含重复类型,这将不再起作用.因此,我想更改 std::get<>
调用以在元组中使用数字索引而不是使用类型.鉴于我的开发环境停留在 C++14 上,有没有办法让它工作?谢谢!
The problem with this is that this will no longer work if Args
contains duplicate types. Hence, I would like to change the std::get<>
call to use numerical indices into the tuple instead of using types. Given that my development environment is stuck on C++14, is there any way of getting this to work? Thanks!
推荐答案
您可以使用带有 std::integer_sequence
来做到这一点.添加一个接受 integer_sequence
之类的辅助函数
You can use a helper function that takes a std::integer_sequence
to do this. Add a helper function that takes an integer_sequence
like
template<typename Tuple, std::size_t... I>
auto foo_helper(const Tuple& a, std::integer_sequence<std::size_t, I...>)
{
return std::make_tuple(bar(std::get<I>(a))...);
}
然后改变 foo
来调用 helper 就像
And then changing foo
to call the helper like
template<typename ... Args>
auto foo(const std::tuple<Args...>& a)
{
return foo_helper(a, std::make_index_sequence<sizeof...(Args)>{});
}
这篇关于如何使用数字索引转换 varadic std::tuple 的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!