对一个对象上的每个元组元素调用函数,无需递归 [英] Call function for each tuple element on one object without recursion

查看:60
本文介绍了对一个对象上的每个元组元素调用函数,无需递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 A 类的对象,可以用不同的类型调用它,并在每次调用时返回更改后的self。出于此问题的目的, A 将会

I have an object of class A that may be called with different types and returns changed self on each call. For purpose of this question A will do

struct A {
    A call(const int&) {
    }
    A call(const string& s) {
    }
    ////
} a;

所以我有一个未知类型的元组:

So I have a tuple of unknown types:

std::tuple<Types...> t;

,我想分别呼叫 a 元组元素,所以我想得到像这样的东西:

and I want to call a with each tuple element, so I want to get something like:

b = a;
b = b.call(get<0>(t));
b = b.call(get<1>(t));
b = b.call(get<2>(t));
//...

b = a.call(get<0>(t)).call(get<1>(t)).call(get<2>(t)...)

订单并不是很重要(我的意思是,如果买权顺序颠倒甚至洗牌也可以) 。

Order is not really important (I mean if call order is reversed of even shuffled it's OK).

我确实知道可以进行递归操作,但这很丑陋。

I do understand that it's possible to do with recursion but it's quite ugly. Is it possible to achieve without recursion?

推荐答案

您可以使用 std :: index_sequence< Is.。 。 ,类似于:

You may use std::index_sequence<Is...>, something like:

namespace detail
{

    template <std::size_t...Is, typename T>
    void a_call(A& a, std::index_sequence<Is...>, const T& t)
    {
        int dummy[] = {0, ((a = a.call(std::get<Is>(t))), void(), 0)...};
        static_cast<void>(dummy); // Avoid warning for unused variable.
    }

}

template <typename ... Ts>
void a_call(A& a, const std::tuple<Ts...>& t)
{
    detail::a_call(a, std::index_sequence_for<Ts...>{}, t);
}

在C ++ 17中,折叠表达式允许:

In C++17, Folding expression allows:

    template <std::size_t...Is, typename T>
    void a_call(A& a, std::index_sequence<Is...>, const T& t)
    {
        (static_cast<void>(a = a.call(std::get<Is>(t))), ...);
    }

,甚至带有 std :: apply

template <typename ... Ts>
void a_call(A& a, const std::tuple<Ts...>& t)
{
    std::apply([&](const auto&... args){ (static_cast<void>(a = a.call(args)), ...); }, t);
}

这篇关于对一个对象上的每个元组元素调用函数,无需递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆