【问题标题】:Compiling error | cannot compile cpp program due to compiler parser编译错误 |由于编译器解析器无法编译 cpp 程序
【发布时间】:2021-03-26 22:57:37
【问题描述】:

简短说明
我正在尝试编译一个简短的 lambda 以将给定输入转换为字符串格式。我的整个班级使用模板,即模板 。我想重载
例如,假设我的对象是 {int age: 12, int* left: null, int* right: null},我应该能够打印类似“{值:“12”,左:未定义,右:未定义}”。另外,如果object = {string comment: "Distance learning....", int* left: undefined, int* right: undefined},我应该打印出来,"{value: "Distance learning....",左:未定义,右:未定义}”。下面是 lambda 函数标记的副本,用于从任何数据类型转换为字符串。

std::function<std::string(T)> toString; //declares the blueprint for the lambda function, notice that I am returning a string, and expecting an object of type T, which can be of any type since i'm using a template. 
    toString = [](T value) -> std::string { //Begins the the body of the function
      if (typeid(std::string).name() == typeid(T).name())
      { // not the best way to do this, but here I am checking that the input is already a string, in which case I do not need to convert or anything. 
        return value; //if the input 'value' is already a string, simply return it. 
      }
      //do some stuff to convert the date into a string

      return; // return the final 'value' in string format. 
    };

~如果我的 cmets 让我感到困惑,请提前道歉。

问题
这个想法在纸上是可行的,但是,当我的数据类型不是字符串类型时,就会出现问题。假设 T == int,遍历代码,将跳过 if 语句,假设我的条件设置正确,我应该向下移动。这意味着当函数蓝图说我将返回一个字符串时,我不会返回一个 int。

但是,当编译器检查我的代码时,它会读取它并认为我正在尝试发回一个 int,而函数应该发回一个字符串并引发错误。 “从'int'类型的返回值到函数返回类型'std::string'的转换没有可行的转换”

例如,

//Let T = int, value = 12, so the below parameter equals, int value, which holds the value of 12. 

    toString = [](T value) -> std::string {
      if (typeid(std::string).name() == typeid(T).name())
      { //should failed since typeid(int).name != typeid(std::string).name
        return value;
      }
      //do some stuff to convert the date into a string

      return; // return the final 'value' in string format. 
    };
//However, when the compiler parses the code, it thinks that I am trying to return value, which is of type int. But the function is supposed to return a string.

//In reality, this should not happen since my if statement will take care of it. 

有没有人知道这个问题的解决方法或关于如何修复我的逻辑的任何想法?

【问题讨论】:

  • 这正是if constexpr 所针对的情况,但您需要使用C++17

标签: c++ c++11


【解决方案1】:

至少需要 C++17 才能使用if constexpr

使用if constexpr,您可以编写如下内容

 if constexpr ( std::is_same_v<T, std::string> )
     return value
 else
  {
     // something else that return a std::string
  }

只有这样你才能从编译中排除return value,当T不是std::string时,以及else的主体,否则。

请注意,我已使用 std::is_same 类型特征来检查 Tstd::string 是否为同一类型。 std::is_same 是编译器决定编译时间的东西。您的 typeid(...).value() 是运行时值。建议:尽可能选择编译时类型特征。

但是我需要看一个更完整的例子来展示如何在你的类/结构中使用if constexpr

在 C++17 之前,需要两个不同的函数来初始化tostring

【讨论】:

  • 感谢您的意见!这个项目我只能用cpp11。
  • @Drio - 所以你必须开发不同的功能。你应该展示更多关于你的班级的东西。
猜你喜欢
  • 2012-11-10
  • 1970-01-01
  • 2013-06-10
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多