【问题标题】:perfect forwading tuple values from std::get来自 std::get 的完美转发元组值
【发布时间】:2018-01-31 00:04:22
【问题描述】:

我有一个类似于std::apply 的很好的实现,它将元组扩展为函数的参数。它工作得很好,除了 std::get 总是返回一个左值并且它无法匹配正确的重载。

POC 代码可以在这里找到:https://wandbox.org/permlink/OUYMQY2afL8vRMUu

这个想法是将std::forward 添加到apply_sequence 以便打印ONE TWO THREE

void printNumber(const int& x, const int& y)
{
    std::cout << "ONE" << std::endl;
}

void printNumber(const int& x, int&& y)
{
    std::cout << "TWO" << std::endl;
}

void printNumber(int&& x, const int& y)
{
    std::cout << "THREE" << std::endl;
}

template<typename... TTuple, std::size_t... Indices>
auto apply_sequence(const std::tuple<TTuple...>& tuple, std::index_sequence<Indices...>)
{
    // missing: forward value to proper type (currently is always lvalue)
    return printNumber(std::get<Indices>(tuple)...);
}

template<typename... TTuple>
auto apply_tuple(const std::tuple<TTuple...>& tuple)
{
    return apply_sequence(tuple, std::index_sequence_for<TTuple...>());
}

int main(int argc, char* argv[])
{
    std::tuple<int, int> one { 1, 2 };
    apply_tuple(one); // ONE

    std::tuple<int, int&&> two { 1, 2 };
    apply_tuple(two); // TWO

    std::tuple<int&&, int> three { 1, 2 };
    apply_tuple(three); // THREE

    return 0;
}

编辑:如果有人想要解决问题https://wandbox.org/permlink/XkUjfypAMepJRPgZ

【问题讨论】:

标签: c++ tuples forward perfect-forwarding


【解决方案1】:

原因是如果元组参数是一个左值,std::get 返回一个左值,即使该元素是一个右值引用。你可以自己写my_get来解决它:

// If the element is not an rvalue reference, behave the same as std::get
template< std::size_t I, class... Types >
constexpr std::enable_if_t <
              !std::is_rvalue_reference_v<std::tuple_element_t<I, std::tuple<Types...>>>, 
               std::tuple_element_t<I, std::tuple<Types...>>const&
          >
    my_get( const std::tuple<Types...>& t ) noexcept
{
    return std::get<I>(t);
}

// If the element is an rvalue reference, move the result of std::get
template< std::size_t I, class... Types >
constexpr std::enable_if_t <
              std::is_rvalue_reference_v<std::tuple_element_t<I, std::tuple<Types...>>>, 
              std::tuple_element_t<I, std::tuple<Types...>>
          >
    my_get( const std::tuple<Types...>& t ) noexcept
{
    return std::move(std::get<I>(t));
}

在您的代码中使用my_get 而不是std::get,那么一切顺利。

【讨论】:

  • 谢谢!我想知道为什么标准std::get没有以这种方式实现,这对我来说毫无意义
猜你喜欢
  • 2020-07-07
  • 2015-09-07
  • 2015-04-11
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 2021-12-17
  • 1970-01-01
相关资源
最近更新 更多