【发布时间】:2018-09-13 08:25:55
【问题描述】:
我想将 C++ 流包装在模板类中,以便为流定义的所有
您能否更改以下代码,使其在不过多改变整体意图的情况下进行编译?
#include <iostream>
class Foo
{
private:
std::ostream& os;
public:
explicit Foo( std::ostream& os ) : os( os ) {};
template<class T>
Foo& operator<<( const T& t )
{
os << t << '!';
return *this;
}
};
int main()
{
Foo( std::cout ) << "test" << '\n'; // works fine
Foo( std::cout ) << "test" << std::endl; // compilation error
return 0;
}
我假设 std::endl 具有某种类型,因此被模板化方法“捕获”。
【问题讨论】:
-
This thread 应该会有所帮助。上下文有点不同(可变参数包),但答案应该阐明问题是什么以及如何缓解它。
-
我需要一个实际编译的例子。
标签: c++ c++11 templates iostream