如何从值元组中生成左值引用元组

时间:2014-09-09 22:35:45

标签: c++

有一些与此主题相关的问题:

How to make a tuple of const references?

std::make_tuple doesn't make references

但两个都没有讨论如何从一个值元组中创建左值引用的元组。

以下是我所得到的:

template <typename... Args>
std::tuple<Args&...> MakeTupleRef(const std::tuple<Args...>& tuple)
{
    return std::tie(tuple); // this fails because std::tie expects a list of arguments, not a tuple.
}

int main()
{
    std::tuple<int, int> tup;
    std::tuple<int&, int&> tup2 = MakeTupleRef(tup); // the values of tup2 should refer to those in tup
    return 0;
}

据我所知,std::tie在这里是理想的,因为它产生左值引用,但它不接受元组作为输入。我怎样才能解决这个问题呢?

1 个答案:

答案 0 :(得分:2)

通常的integer_sequence技巧:

template <typename... Args, std::size_t... Is>
std::tuple<Args&...> MakeTupleRef(std::tuple<Args...>& tuple, std::index_sequence<Is...>)
{
    return std::tie(std::get<Is>(tuple)...);
}


template <typename... Args>
std::tuple<Args&...> MakeTupleRef(std::tuple<Args...>& tuple)
{
    return MakeTupleRef(tuple, std::make_index_sequence<sizeof...(Args)>());
}

如果知道元组中的类型是唯一的,那么有一个更简单的替代方法:

template <typename... Args>
std::tuple<Args&...> MakeTupleRef(std::tuple<Args...>& tuple)
{
    return std::tie(std::get<Args>(tuple)...);
}