![](/img/trans.png)
[英]Addressing the ith member of a std::tuple when i is not a constant expression?
[英]Transform ith element of std::tuple
有没有简单的方法来实现下面的伪代码? 还是您 go 掉了一个模板元编程兔子洞?
template <size_t index, typename Func, typename... Args>
auto transform(std::tuple<Args...> tup, Func fn)
{
return std::tuple{ tup[0], ..., tup[index - 1], fn(tup[index]), ... };
}
使用模板 lambda 展开tuple
,并根据当前元素的索引选择是否应用 function
#include <tuple>
template<size_t index, size_t I, typename Func, typename Tuple>
auto transform_helper(Tuple& tup, Func& fn) {
if constexpr (I < index)
return std::get<I>(tup);
else
return fn(std::get<I>(tup));
}
template<size_t index, typename Func, typename... Args>
auto transform(std::tuple<Args...> tup, Func fn) {
return [&]<std::size_t... I>(std::index_sequence<I...>) {
return std::tuple{transform_helper<index, I>(tup, fn)... };
}(std::index_sequence_for<Args...>{});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.