将 ostream 包装在类中并模板化<<运算符
Wrap ostream in class and templatize << operator
我想将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 具有某种类型,因此被模板化方法"捕获"。
正如 kmdreko 所建议的,您需要为模板函数添加重载
(std::endl 是一个模板函数,而不是一个类或简单类型(
喜欢这个:
#include <iostream>
class Foo
{
private:
std::ostream& os;
public:
explicit Foo(std::ostream& os) : os(os) {};
// for classes
template<class T>
Foo& operator<<(const T& t)
{
os << t << '!';
return *this;
}
// for endl
Foo& operator<<(std::ostream& (*pf) (std::ostream&)) {
os << pf;
return *this;
}
};
您可能应该用 SFINAE 保护它并完善参数。
template<class T> auto operator<<(T &&t)
-> decltype(os << std::forward<T>(t) << '!', *this)
{
return os << std::forward<T>(t) << '!', *this;
}
现在,这应该接受std::ostream
可以打印并且无法与其他所有内容一起编译的每个参数。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多