Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 操作员<&书信电报;无法输出std::endl--Fix?_C++_Templates_Stl_Operator Overloading - Fatal编程技术网

C++ 操作员<&书信电报;无法输出std::endl--Fix?

C++ 操作员<&书信电报;无法输出std::endl--Fix?,c++,templates,stl,operator-overloading,C++,Templates,Stl,Operator Overloading,下面的代码给出了一个错误,它应该只输出std::endl: #include <iostream> #include <sstream> struct MyStream { std::ostream* out_; MyStream(std::ostream* out) : out_(out) {} std::ostream& operator<<(const std::string& s) { (*out_) <&l

下面的代码给出了一个错误,它应该只输出
std::endl

#include <iostream>
#include <sstream>

struct MyStream {
  std::ostream* out_;
  MyStream(std::ostream* out) : out_(out) {}
  std::ostream& operator<<(const std::string& s) {
    (*out_) << s;
    return *out_;
  }
};

template<class OutputStream>
struct Foo {
  OutputStream* out_;
  Foo(OutputStream* out) : out_(out) {}
  void test() {
    (*out_) << "OK" << std::endl;
    (*out_) << std::endl; // ERROR     
  }
};

int main(int argc, char** argv){
  MyStream out(&std::cout);
  Foo<MyStream> foo(&out);
  foo.test();
  return EXIT_SUCCESS;
}

我怎样才能使代码工作?谢谢

您需要将此添加到您的
结构MyStream

  std::ostream& operator<<( std::ostream& (*f)(std::ostream&) )
  {
      return f(*out_);
  }
将正确输出

start done 开始 完成
谢谢,这太疯狂了。一个人怎么会知道呢?应该有一个类可以从中派生出来,它会自动添加这些难看的东西。这是因为C++模板系统对指针类型有一些特殊的规则。(我想它们是模棱两可的?)@dehmann:我不知道怎么会有人知道这一点。我不得不尝试一些不同的谷歌搜索,以获得正确的方向,然后我仍然必须拼凑出答案。希望这能在这种情况下帮助更多的人。它不是一个函数,而是一个函数模板(因此它不是特定于
ostream
,但也适用于
wostream
和其他人)。这就是为什么简单的
T
不起作用的原因。
  std::ostream& operator<<( std::ostream& (*f)(std::ostream&) )
  {
      return f(*out_);
  }
  void test() {
    (*out_) << "start";
    (*out_) << std::endl;
    (*out_) << "done";
  }
start done