【发布时间】: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