创建行为类似于字符串流的类的最简单方法
Simplest way to create class that behaves like stringstream
我正在制作一个简单的Error
类,应该使用throw
语句抛出,记录或写入控制台。用法的基本思想是:
//const char* filename is function argument
if(!file_exists(filename))
throw Error(line, file, severity)<<"Invalid argument: the file does not exist: "<<filename;
我原本想扩展stringstream
,但我的搜索表明不可能在流上扩展。
我真的很想让错误类像你在上面看到的那样方便,这意味着能够"吃"各种类型并将它们附加到内部错误消息中。
所以实际上这并不难。你不能直接从stringstream
继承——或者我只是不知道怎么做。你很快就会淹没在std
模板系统中......
template<class _Elem,
class _Traits,
class _Alloc>
// ... mom help me!
但是,您可以制作一个模板:
template <class T>
Error& Error::operator<<(T const& value) {
//private std::stringstream message
message<<value;
//You can also trigger code for every call - neat, ain't it?
}
您将此方法中的所有值添加到类中的私有变量:
class Error
{
public:
Error(int, const char*, int);
~Error(void);
std::string file;
unsigned int line;
//Returns message.str()
std::string what();
//Calls message.operator<<()
template <class T>
Error& operator<< (T const& rhs);
private:
std::stringstream message;
};
我仍然缺少一些东西 - 如何区分 stringstream
和其他人支持的类型,并在调用线上而不是在类Error
抛出错误。我还想为不受支持的类型编写自己的处理程序。
相关文章:
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- boost::variant - 对变体应用算术的最简单方法
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 从 txt 文件中读取数据的最简单方法
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 对于我扩展此程序来计算最高10x10矩阵的倒数的最简单方法是什么
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 编写要在 Python 中使用的并行 C/C++ 模块的最简单方法
- 开放式颜色多边形表面的最简单方法
- 确定代码中当前程序集是否为 32/64 位的最简单方法
- 将unique_ptr存储在堆上的最简单方法是什么
- 使用 C# 获取 OpenGL 版本的最简单方法
- 在自定义 C/C++ 程序中获取 PPP0 接口 Tx/Rx 字节的最简单方法是什么?
- 为depth_first_search定义颜色图的最简单方法