c++(类型扣除编译时错误)

c++ (type deduction compile time error)

本文关键字:编译时错误 类型 c++      更新时间:2023-10-16

我试图实现对XML阅读器的解析,我有一个函数或一组函数,实现了从XML文件中获取值和设置变量所需的解析,我已经实现了几个通用的模板化函数,但我被困在编译错误中,编译器试图替换方法中模板化的所有函数并生成编译时错误(类型推断)。我试图指示编译器,每个分支是一个不同的情况下显式的类型,但不工作,这里是代码:

#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);

it动作产生更多编译错误。编译器:

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'");
  }
}

alpha_to_bool外,本程序中的所有函数均为模板函数。这意味着当从隐式特化set_option<int>调用alpha_to_bool时,它将以int*作为参数调用,但它当然需要bool*

我解决这个问题:这一行就是问题所在:

if(type=="bool") alpha_to_bool(aValuePtr,aValue);

and I change for this

if(type=="bool") alpha_to_bool(reinterpret_cast<bool *>(aValuePtr),aValue);

它编译和工作,但我仍然不明白为什么编译器试图推断错误的类型.......