嘗試寫例外模板構造函數類,因此拋出異常的時候,我可以把可變長度參數,來到某事像這樣:模板的構造
namespace miniReader{
namespace Exception{
template<typename deriverEx, typename baseType>
class Exception : public baseType{
std::string errorClass;
mutable std::string exStrMsg;
protected:
static std::stringstream exMsg;
std::string whatMessage;
// Exception(const Exception& other): baseType(""){}
const char* what() const noexcept{
if(exStrMsg.empty()){
exStrMsg = exMsg.str();
}
exMsg.str("");
return exStrMsg.c_str();
}
~Exception() noexcept {
}
public:
Exception(): baseType("") {
}
};
class miniRuntimeException : public Exception<miniRuntimeException, std::runtime_error>{
public:
miniRuntimeException(): Exception() {}
template<typename T, typename...Args>
miniRuntimeException(T first, Args...arg): Exception(){
LOG(first, this);
exMsg << first << " ";
miniRuntimeException(arg...);
}
};
template<typename deriverEx, typename baseType>
std::stringstream Exception<deriverEx, baseType>::exMsg;
}
}
現在我可以寫拋出異常這樣的:
miniRuntimeException(__FILE__, __LINE__, "Failed opening file", "Runtime Exception")
我已經做了exMsg靜態,因爲在其他情況下,我可以得到所有的模板參數。所以我的問題是,Exception類中的exMsg是靜態的,所以當派生類構造函數被調用時(variadic模板),讀取參數是正確的。我找不到一種方法使它不是靜態的,因爲exMsg只會得到一個模板參數。有沒有辦法做到這一點?接下來的問題是當我的模板構造函數被調用時,爲每個參數創建新對象(是否正確?)以及如何在這種情況下我可以在這些對象之間傳遞信息,如更新exMsg,因此它將在最終對象中完成?
你的問題一般不是很清楚...... – callyalater