创建行为类似于字符串流的类的最简单方法

Simplest way to create class that behaves like stringstream

本文关键字:最简单 方法 字符串 类似于 创建      更新时间:2023-10-16

我正在制作一个简单的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抛出错误。我还想为不受支持的类型编写自己的处理程序。