[英]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.