【问题标题】:C++ should I use forwarding references?C++ 我应该使用转发引用吗?
【发布时间】:2021-12-16 13:37:55
【问题描述】:

我有接受值并将它们传递给其他函数的函数。没有人会关心它是否是一个右值引用,他们只想读取这个值。我需要使用转发引用还是可以像这样使用const&

template<class Arg>
void printOne(std::string& str, std::string_view fmt, const Arg& arg) {
  if constexpr (std::is_same<char, Arg>::value) {
    // ...
  } else if constexpr (...) {
    // ...
  } 
}

template<class ...Args>
std::string printFormatted(std::string_view fmt, const Args& ...args) {
  std::string str;
  (printOne(str, fmt, args), ...);
  return str;
}

【问题讨论】:

    标签: c++ templates perfect-forwarding forwarding-reference


    【解决方案1】:

    不,您不必使用转发引用。 const 引用绑定到临时右值,因此通常当不需要移动语义或完美转发时,普通的、普通的 const 引用将起作用。

    【讨论】:

      猜你喜欢
      • 2017-10-01
      • 2012-08-09
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 1970-01-01
      相关资源
      最近更新 更多