gpt4 book ai didi

c++模板-(类型推导编译时错误)

转载 作者:行者123 更新时间:2023-11-28 06:15:04 25 4
gpt4 key购买 nike

我试图实现对 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;
}

代码没有编译,我猜不出为什么,有什么方法可以指示编译器代码的每个分支都是不同的情况,并且它不能尝试推断所有情况的类型?提前致谢

此外,我试图向编译器指示类型,例如:

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不可能工作,因为它们传递的指针指向 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'");
}
}

其余类型也类似。

关于c++模板-(类型推导编译时错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30486379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com