使用尾随返回类型防止悬空右值引用

时间:2012-07-04 09:16:17

标签: c++ c++11 rvalue-reference

此功能正常:

std::string get_str() {
  return std::get<0>( make_tuple(std::string("hi")) );
}

但是如果你试图用decltype定义的尾随返回类型做同样的事情,该函数返回一个悬空的右值引用

auto get_str() -> decltype( std::get<0>( make_tuple(std::string("hi")) ) ) {
  return std::get<0>( make_tuple(std::string("hi")) );
}

我有一个很酷的尾随返回类型应用程序,我想使用std::get。不幸的是,在这种情况下,std::get 的返回类型是一个右值引用,因此decltype正在执行其工作......

您是否知道使用尾随返回类型和decltype的方法,但避免悬空的右值参考?

3 个答案:

答案 0 :(得分:3)

使用std::remove_reference

auto get_str() -> 
std::remove_reference<
    decltype( std::get<0>( make_tuple(std::string("hi")) ) )
    >::type {
  return std::get<0>( make_tuple(std::string("hi")) );
}

答案 1 :(得分:3)

听起来好像你想要std::remove_reference。 因此,在您的情况下,只需将您的尾随返回类型更改为
std::remove_reference<decltype( std::get<0>( make_tuple(std::string("hi")) ) )>::type

答案 2 :(得分:3)

您可以使用标准remove_reference类型特征

删除引用
#include <string>
#include <tuple>
#include <type_traits>

auto get_str() ->
    std::remove_reference<
        decltype( std::get<0>( make_tuple( std::string("hi") ) ) )
    >::type
{
    return std::get<0>( make_tuple( std::string("hi") ) );
}
相关问题