[英]c++ templates - (type deduction compile time error)
我試圖實現對xml閱讀器的解析,並且我有一個函數或一組函數實現了從de xml文件中獲取de值並設置變量所必需的解析,我已經實現了幾個模板化函數,供通用使用,但是我陷入了編譯錯誤中,編譯器試圖替換該方法中模板化的所有函數並生成編譯時錯誤(類型推斷)。 我試圖通過顯式向編譯器指示每個分支是不同的情況,但不起作用,下面是代碼:
#include <string>
#include <stdexcept>
#include <sstream>
namespace
{
int cantidad_repeticiones;
int execution_code;
bool should_report;
bool time_stamp;
std::string cmd_description;
int cmd_id;
unsigned delay_entre_comandos;
void alpha_to_bool(bool *aBool,const std::string & aString)
{
std::istringstream(aString) >> std::boolalpha >> (*aBool);
}
template<typename T>
void convertoToNumber( T * aNumber, const std::string & aString)
{
std::stringstream mStringstream(aString);
mStringstream >> (*aNumber);
}
template<typename T>
void set_option(T * aValuePtr,const char * xml_type,const char * xml_value )
{
std::string type(xml_type);
std::string aValue(xml_value);
if(type=="float") convertoToNumber(aValuePtr,aValue);
if(type=="bool") alpha_to_bool(aValuePtr,aValue);
if(type=="int") convertoToNumber(aValuePtr,aValue);
if(type=="unsigned") convertoToNumber(aValuePtr,aValue);
if(type=="double") convertoToNumber(aValuePtr,aValue);
}
void parse_xml_option(const char * xml_option,const char * xml_type,const char * xml_value)
{
std::string string_cache(xml_option);
if(string_cache=="timestamp") set_option(&time_stamp,xml_type,xml_value);
if(string_cache=="repeticiones") set_option(&cantidad_repeticiones,xml_type,xml_value);
if(string_cache=="delay_entre_comandos") set_option(&delay_entre_comandos,xml_type,xml_value);
if(string_cache=="generate_report") set_option(&should_report,xml_type,xml_value);
}
}
int main()
{
return 0;
}
代碼沒有編譯,我不知道為什么,有什么辦法表明編譯器代碼的每個分支都是不同的情況,並且它無法嘗試推斷所有情況的類型? 提前Thx
另外,我試圖向編譯器指出類型,例如:
if(type=="float") convertoToNumber<float>(aValuePtr,aValue);
它會產生更多的編譯錯誤。 編譯出:
cannot convert 'int*' to 'bool*' for argument '1' to 'void {anonymous}::alpha_to_bool(bool*, const string&)'
note: no known conversion for argument 1 from 'bool' to 'bool&'
表示該行:
if(type=="bool") alpha_to_bool(aValuePtr,aValue);
有錯誤
無論T
是什么,當編譯器編譯set_option<T>
,它都必須編譯表達式alpha_to_bool(aValuePtr, aValue)
。
自然地,當T
不是bool
時,這將很不起作用,因此您對set_option
的調用的set_option
可能無法工作,因為它們傳遞了指向bool
以外的類型的指針。
您應該重載 set_option或其他類似方法:
void set_option(bool * aValuePtr,const char * xml_type,const char * xml_value )
{
std::string type(xml_type);
std::string aValue(xml_value);
if(type=="bool") {
alpha_to_bool(aValuePtr,aValue);
} else {
throw std::runtime_error("Attempted to assign " + type + " to a `bool'");
}
}
對於其余類型也是如此。
我解決了這個問題:這是問題所在:
if(type=="bool") alpha_to_bool(aValuePtr,aValue);
我為此更改:
if(type=="bool") alpha_to_bool(reinterpret_cast<bool *>(aValuePtr),aValue);
它可以編譯和工作,但是我還是不明白為什么編譯器試圖推斷錯誤的類型。
除了alpha_to_bool
之外,此程序中的所有函數都是模板函數。 這意味着,當alpha_to_bool
從隱專業化稱為set_option<int>
它被稱為具有一個int *作為它的參數,但它當然需要一個bool *
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.