2016-05-03 57 views
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; 
     } 
    } 
    } 
} 
+0

必须在编译时从函数的签名中提供的信息及其调用站点中知道'T'。它一次只能是一种类型。 – Quentin

+0

同意,调用此函数是这样的 int l = getProperty (1,root); char name [50]; sprintf(名称,“%s”,getProperty (2,root)); – sach

+0

噢,如你所说模板是编译时间的东西。这不会起作用 – sach

回答

0

如果您使用C++ 14,这个简单的例子确实工作

template <typename T> 
auto test(T a){ 
    return a; 
} 

int main() 
{ 
    int a = 1; 
    std::cout << test(a) << std::endl; 
    double b = 2.0; 
    std::cout << test(b) << std::endl; 
    std::string s {"ss"}; 
    std::cout << test(s) << std::endl; 
} 
当然

,你需要知道你想要检索的类型在通话之前,这可能不是你要实现的目标