簡體   English   中英

創建行為類似於stringstream的類的最簡單方法

[英]Simplest way to create class that behaves like stringstream

我正在制作一個簡單的Error類,該類應該使用throw語句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 ,但是我的搜索表明無法在stream上擴展

我真的很想使錯誤類如您在上面看到的那樣方便,這意味着能夠“ 吃掉 ”各種類型並將它們附加到內部錯誤消息中。

因此實際上並不難。 您不能直接從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類中拋出錯誤。 我也想為不支持的類型編寫自己的處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM