0
我想写一个函数,它会根据某些条件返回我String
,Int
,Float
。使用C11。尝试过几个已经提到的东西,不适用于模板/汽车。如果该函数只有一个返回,那么它现在就罚款。当我添加另一个返回说字符串,编译错误。错误:从int
无效转换为char*
基于输入返回不同类型的函数
template<typename T>
T getProperty(int field,Json::Value root)
{
for(int i =0;i < root["properties"].size(); i++)
{
if(root["properties"][i]["field"].asInt() == field)
{
if(strcmp(root["properties"][i]["type"].asString().c_str(),"int") == 0)
{
T convertedValue = (root["properties"][i]["currVal"].asInt());
return convertedValue;
}
if(strcmp(root["properties"][i]["type"].asString().c_str(),"string") == 0)
{
T convertedValue;
sprintf(convertedValue,"%s",root["properties"][i]["currVal"].asString().c_str());
return convertedValue;
}
}
}
}
必须在编译时从函数的签名中提供的信息及其调用站点中知道'T'。它一次只能是一种类型。 – Quentin
同意,调用此函数是这样的 int l = getProperty(1,root); char name [50]; sprintf(名称,“%s”,getProperty (2,root)); –
sach
噢,如你所说模板是编译时间的东西。这不会起作用 – sach