包装 ostream 的正确模板方法
correct template method to wrap a ostream
给定一个类
class ostreamWrapper
{
private:
ostream * str;
public:
ostreamWrapper operator << (const char *);
}
其中ostream * str
将指向 std::cout,ostreamWrapper operator << (const char *)
将给定的文本发送到包装的 ostream str
。
在这种情况下,我只能instance << "const char * text"
,而不能使用其他可打印的数据。不像直接<<
std::cout 或 std::cerr。
如何实现运算符方法,以便它接受任何类型的数据,就像 std::cout 或 std::cerr 直接做的那样?
首先,编写一个公共operator<<
模板,以便它可以接受任何类型,并简单地将其转发到包装的ostream
。
template <class T>
ostreamWrapper& operator<<(T&& x) {
*str << std::forward<T>(x);
return *this;
}
其次,为了接受插入流操纵器模板(如 std::endl
(,添加第二个公共operator<<
,专门接受用于包装ostream
的操纵器:
ostreamWrapper& operator<<(ostream& (*manip)(ostream&)) {
*str << manip;
return *this;
}
省略第二个重载将导致插入过载的操纵器或操纵器模板失败,并显示"不明确的重载"或类似的错误消息。
请参阅建议的实现示例,它将推断模板参数类型并相应地打印,如果您可以使用 C++11 请参阅@Brian答案:
#include <iostream>
using namespace std;
class ostreamWrapper {
private:
ostream* str;
public:
ostreamWrapper(ostream* str_v) : str(str_v) {}
template <typename T>
ostreamWrapper& operator<<(const T& t) {
if (str)
*str << t;
return *this;
}
};
int main() {
ostreamWrapper osw(&std::cout);
osw << 1 << " texto " << std::string(" otro texto ") << 1.2345;
return 0;
}
相关文章:
- 将成员函数指针作为参数传递给模板方法
- 模板方法访问正向声明的类仅在没有此指针的情况下无法编译
- C++11:模板方法的模板函数调用无法编译?
- 如何从ECS中的模板方法获取组件?
- 使用 SFINAE 设计模板方法
- 一个模板方法,用于同时接受常量和非常量参数
- C++模板方法中的循环依赖关系
- 在 C++ 中使用模板方法重写类方法
- 类中的模板方法
- 基于枚举参数调用专用模板方法
- 模板中的模板方法 - 实例声明和类方法声明签名不同
- 可变参数模板方法
- 使用模板方法为标头提供空 cpp 时出现问题
- SFINAE 方法在 clang 中完全禁用基类的模板方法
- 将函数和成员函数传递给模板方法
- 从非模板类调用专用模板方法
- MSVC使用constexpr-if从可变模板方法中的基本模板参数中吞下const
- 依赖于特定类类型的C++模板方法
- 有没有办法仅在两个模板参数相同时才覆盖匹配的模板方法?
- 包装 ostream 的正确模板方法