【问题标题】:binary '<<' : no operator found which takes a left-hand operand of type 'std::basic_ostream<char, std::char_traits<char>>'二进制 '<<' :未找到采用 'std::basic_ostream<char, std::char_traits<char>>' 类型的左操作数的运算符
【发布时间】:2018-10-05 09:04:39
【问题描述】:

有一个函数将 std::ostream& 作为参数并执行一些操作:

inline std::ostream& my_function(std::ostream& os, int n) {
      // some operations
      return os;    
}

还有另一个函数调用my_function

void caller_function(int  n) {
    std::ostringstream ostsr;
    ostsr << my_function(ostsr, n);
}

visual studio 2015编译器报错:

error C2679: binary '<<' : no operator found which takes a left-hand operand of type 'std::basic_ostream<char, std::char_traits<char>>' 

std::ostringstreamm 有一个继承和重载的operator&lt;&lt;,它在这种情况下采用操纵器函数,操纵器函数是my_function 重载运算符

ostream& operator<< (ostream& (*pf)(ostream&));

那么问题是什么以及如何解决?

【问题讨论】:

  • my_function(ostsr, n) 不是操纵器函数。这是一个流引用。 my_function一个函数但是签名错误。

标签: c++ compiler-errors operator-overloading ostream ostringstream


【解决方案1】:

您的函数与ostream&amp; (*pf)(ostream&amp;) 不匹配,而是ostream&amp; (*pf)(ostream&amp;, int)。您将不得不以某种方式绑定第二个参数。不过,为此目的使用 lambda 会很困难,因为如果您捕获(并使用)任何东西,such as n in your case,则 lambda 不能再衰减到函数指针 as it otherwise could

我看不到一种可重入方式,您可以将操纵器重载与运行时参数(如 n)一起使用,因为任何匹配 ostream&amp; (*pf)(ostream&amp;) 的东西都不能有状态(或充其量依赖于一些全局的,这是丑陋且不安全的)和也无法通过参数获取附加信息。

(正如 n.m. 在 cmets 中指出的那样,您也没有将函数传递给 &lt;&lt;,而是将其返回值传递给,这不是您想要的)。

【讨论】:

  • 或者可以直接写my_function(ostsr, n);(不是&lt;&lt;)然后收工。
  • 当我像这样调用 my_function 时它开始工作: ostsr
  • @user37014 你在那里做的是将指针指向返回的std::ostream&amp;。您最终将打印指针(在调用函数之后)。我不认为那是你想要的。
  • 这还能怎么做?当我写 std::ostream l = my_function (ostsr, n) 然后 ostsr
  • @user37014 你想要做的是创建一个ostsr 的副本(命名为l)(由my_function 返回)。编译器告诉您,不允许对其进行复制。要获得“还能如何做到”的答案,您必须首先描述“这个”是什么。正如我的回答中提到的,没有办法将my_function(ostream&amp;, int)ostream&amp; (*pf)(ostream&amp;) 结合在一起。但大概这不是你的实际目标——你想实现一些更大的目标(你没有解释过)。见XY problem
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多