c++ - 是否有用于右值引用的 reference_wrapper<>?

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

我想知道如何完成以下操作

void f(string &&s) { 
  std::string i(move(s)); 
  /* other stuff */ 
} 

int main() { 
  std::string s; 
  bind(f, s)(); // Error.
  bind(f, move(s))(); // Error.
  bind(f, ref(s))(); // Error.
}

如何传递右值引用并将其作为右值引用(可能被包装)存储在调用包装器中?我知道我可以手动写一个像 std::reference_wrapper<> 这样的类具有到 T&& 的转换功能,但我宁愿避免这种情况并使用标准技术。


我按照 AProgrammer 的建议实现了它:

template<typename T> struct adv { 
  T t; 
  explicit adv(T &&t):t(forward<T>(t)) {} 
  template<typename ...U> T &&operator()(U &&...) { 
    return forward<T>(t); 
  } 
}; 

template<typename T> adv<T> make_adv(T &&t) { 
  return adv<T>{forward<T>(t)}; 
}

namespace std { 
  template<typename T> 
  struct is_bind_expression< adv<T> > : std::true_type {}; 
} 

现在我可以说

void f(string &&s) { 
  std::string i(move(s)); 
  /* other stuff */ 
} 

int main() { 
  std::string s; 
  bind(f, make_adv(move(s)))(); // Works!
}

如果我们将左值传递给 make_adv , 它会将其作为左值转发给输入参数,因此它可以用作 std::ref 的替代品, 在这种情况下。

最佳答案

我对此的看法。

N3225 中的 20.8.10.1.2/10

The values of the bound arguments v1, v2, ..., vN and their corresponding types V1, V2, ..., VN depend on the types TiD derived from the call to bind and the cv-qualifiers cv of the call wrapper g as follows:

  • if TiD is reference_wrapper, the argument is tid.get() and its type Vi is T&;
  • if the value of is_bind_expression::value is true, the argument is tid(std::forward(uj)...) and its type Vi is result_of::type;
  • if the value j of is_placeholder::value is not zero, the argument is std::forward(uj) and its type Vi is Uj&&;
  • otherwise, the value is tid and its type Vi is TiD cv &.

所以拥有右值引用的唯一可能性是拥有is_bind_expression<TiD>::value真或 is_placeholder<TiD>::value不为零。第二种可能性具有您不想要的含义,并且第一种可能性获得想要的结果意味着如果我们限制为标准提供的类型,我们试图解决的问题就解决了。因此,唯一的可能性是提供您自己的包装器和 is_bind_expression<TiD> 的特化。 (这是 20.8.10.1.1/1 允许的)因为我没有看到。

关于c++ - 是否有用于右值引用的 reference_wrapper<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24139928/

相关文章:

c++ - Qt 不识别其他子项目

c++ - 未定义的成员函数引用 (C++)

c++ - 将值分配给以元组为值的嵌套映射时出错

c++ - 如何在 C++ 中使用右值引用来避免不必要的实例

c++ - 简单的 C++ SFML 程序高 CPU 使用率

c++ - std::vector push_back() 删除前一个元素

c++ - 检查 C++ 成员函数是否存在,可能 protected

c++ - 通过右值引用返回更有效吗?

c++ - 使用通用引用时的类型推导

c++ - 计算第一次,加载第二次模式