首页 > 解决方案 > 将元组的部分解包为函数参数

问题描述

想象一下,我有tuple<...>几种类型。而且我想将元组的值部分扩展为具有静态参数的函数的参数 - 即不一定是可变参数,以便函数参数应该与元组部分匹配。我怎样才能做到这一点 ?

标签: c++c++11stdtuple

解决方案


不确定您的问题到底是什么(您下次可以显示一些代码吗?)。但是您可以使用结构化绑定来“解包”这样的元组:

#include <tuple>
#include <iostream>

void f(int x, double y)
{
    std::cout << x << ", " << y << "\n";
}

template<typename... args_t>
void g(const std::tuple<args_t...>& args)
{
    // C++17
    //const auto [x, y] = args;

    // C++11
    auto x = std::get<0>(args);
    auto y = std::get<1>(args);

    f(x, y);
}

int main()
{
    auto tuple = std::make_tuple( 1,3.14159265 );
    g(tuple);
}

推荐阅读