问题描述
简短说明
我正在尝试编译一个简短的 lambda 来将给定的输入转换为字符串格式。我的整个班级使用模板,即模板
比如,假设我的对象是{int age: 12,int* left: null,int* right: null},我应该可以打印类似于“{value:”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.
};
~如果我的评论令人困惑,请提前道歉。
问题
这个想法在纸上可行,但是,当我有一个不是字符串类型的数据类型时,就会出现问题。假设 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.
有没有人知道解决这个问题的方法或关于如何解决我的逻辑的任何想法?
解决方法
您至少需要 C++17 才能使用 nat[10]
。
使用 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
和 T
是否为相同类型。 std::string
是编译器决定编译时间的东西。您的 std::is_same
是一个运行时值。建议:尽可能选择编译时类型特征。
但我需要看一个更完整的例子来展示如何在你的类/结构中使用 typeid(...).value()
。
在 C++17 之前,您需要两个不同的函数来初始化 if constexpr
。