gpt4 book ai didi

c++ - 为多个元组的每个第 n 个参数调用一个 lambda?

转载 作者:行者123 更新时间:2023-12-03 07:23:07 25 4
gpt4 key购买 nike

我正在尝试编写一个代码,该代码使用从一组可变元组中提取的输入参数调用 lambda。但是,我的尝试没有编译:

#include <iostream>
#include <tuple>
#include <utility>
#include <type_traits>

template <typename ...>
struct first_of;

template <typename T, typename ... Args>
struct first_of<T, Args...> {
using type = std::decay_t<T>;
};

template <typename T>
struct first_of<T> {
using type = std::decay_t<T>;
};

template <typename ... T>
using first_of_t = typename first_of<T...>::type;

template <typename Fn, typename... Tuples, std::size_t... Idxs>
void run_impl(Fn&& fn, std::index_sequence<Idxs...>, Tuples... t) {
auto temp = {(fn(std::get<Idxs>(t)...), true)...};
(void)temp;
}

template <typename Fn, typename... Tuples>
void run(Fn&& fn, Tuples&&... tuples) {
run_impl(std::forward<Fn>(fn), std::make_index_sequence<std::tuple_size<first_of_t<Tuples...>>::value>{}, std::forward<Tuples>(tuples)...);
}

int main() {
auto a = std::make_tuple(1, 2.34, "one");
auto b = std::make_tuple(32, 5.34, "two");

auto print = [](auto& f, auto& g) { std::cout << f << ", " << g << std::endl; };
run(print, a, b);
}
我期待以下输出:

1, 32
2.34, 5.34
one, two


我正在使用 c++14,所以不幸的是,没有折叠表达式。
这是代码的上帝 bolt 链接: https://godbolt.org/z/G19n5z

最佳答案

最简单的方法是添加另一个间接层,具有 run_impl委托(delegate)给执行实际调用的另一个函数。我冒昧地将您的函数重命名为 call_transposed() :

template <std::size_t I, typename Fn, typename... Tuples>
void call_with_nth(Fn&& fn, Tuples&&... t) {
fn(std::get<I>(std::forward<Tuples>(t))...);
}

template <typename Fn, std::size_t... Idxs, typename... Tuples>
void call_transposed_impl(Fn&& fn, std::index_sequence<Idxs...>, Tuples&&... t) {
auto temp = {(call_with_nth<Idxs>(fn, std::forward<Tuples>(t)...), true)...};
(void)temp;
}

template <typename Fn, typename... Tuples>
void call_transposed(Fn&& fn, Tuples&&... tuples) {
call_transposed_impl(
std::forward<Fn>(fn),
std::make_index_sequence<std::tuple_size<first_of_t<Tuples...>>::value>{},
std::forward<Tuples>(tuples)...);
}
Godbolt link
我不确定您的代码为什么不起作用,但我怀疑 std::get<Idxs>(t)...正在尝试扩展这两个包 Idxst同时,让您以后无需扩展包。这段代码通过一次只处理一个包来避免这个问题。

关于c++ - 为多个元组的每个第 n 个参数调用一个 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64491455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com