【问题标题】:How to call a function using a std::tuple's values as the arguments? [duplicate]如何使用 std::tuple 的值作为参数调用函数? [复制]
【发布时间】:2014-08-30 17:41:23
【问题描述】:
#include <tuple>

using namespace std;

int f(int a, int b)
{
    return a + b;
}

int main() 
{    
    auto t = make_tuple(1, 2);

    return f(magic_xxx(t)); // How to implement magic_xxx?
}

我想要的是让f(magic_xxx(t))等价于f(1, 2),如何实现?

【问题讨论】:

    标签: c++ function c++11 tuples perfect-forwarding


    【解决方案1】:

    一种方法:

    #define TUPLE_VALUES_1(t) std::get<0>(t)
    #define TUPLE_VALUES_2(t) TUPLE_VALUES_1(t), std::get<1>(t)
    #define TUPLE_VALUES_3(t) TUPLE_VALUES_2(t), std::get<2>(t)
    
    
    f(TUPLE_VALUES_2(t));
    

    更新

    link from T.C.'s comment 有一个更好的解决方案。通过在它周围添加一个包装函数,您可以得到您想要的。

    #include <tuple>
    #include <iostream>
    using std::cout;
    using std::endl;
    
    // --------------------
    // BEGIN borrowed code 
    // --------------------
    template<int ...> struct seq {};
    
    template<int N, int ...S> struct gens : gens<N-1, N-1, S...> {};
    
    template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
    
    template <typename Ret, typename ...Args>
    struct Dispatcher
    {
       template<int ...S>
       Ret callFunc(seq<S...>)
       {
          return func_(std::get<S>(params_) ...);
       }
    
       std::tuple<Args...> params_;
       Ret (*func_)(Args...);
    };
    // --------------------
    // END borrowed code 
    // --------------------
    
    // Wrapper function
    template <typename Ret, typename ...Args>
    Ret callFunc(std::tuple<Args...> t, Ret (*func)(Args...))
    {
       Dispatcher<Ret, Args...> disp = {t, func};
       return disp.callFunc(typename gens<sizeof...(Args)>::type());
    }
    
    // ---------------------
    // BEGIN Test functions
    // ---------------------
    
    double foo(int x, float y, double z)
    {
       return x + y + z;
    }
    
    int bar(int a, int b)
    {
       return a + b;
    }
    
    void baz(int a)
    {
    }
    
    void test1()
    {
      auto t = std::make_tuple<int, float, double>(1, 1.2, 5);
      cout << callFunc(t, foo) << endl;
    }
    
    void test2()
    {
       auto t = std::make_tuple<int, int>(1, 2);
       cout << callFunc(t, bar) << endl;
    }
    
    void test3()
    {
       auto t = std::make_tuple<int>(2);
       callFunc(t, baz);
    }
    // ---------------------
    // END Test functions
    // ---------------------
    
    int main(void)
    {
       // Test the functionality
       test1();
       test2();
       test3();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 2017-02-20
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多