函数根据输入返回不同的类型

Function to return different types based on input

本文关键字:类型 返回 输入 函数      更新时间:2023-10-16

我想写一个函数,根据一些条件返回StringIntFloat。使用C11。尝试了一些已经提到的东西,不适用于template/auto。如果函数只有一个返回,那么它现在很好。当我添加另一个返回字符串时,编译错误。错误:从intchar* 的转换无效

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;
      }
    }
  }
}

如果您使用的是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;
}

当然,在调用之前,您需要知道要检索的类型,而这可能不是您想要实现的

您可以使用boost::variant<string, float, int>/boost::any作为返回类型。

请注意,这些类是C++17标准库的一部分。

您可以通过完全专业化模板来实现。但是,您可能应该将查找正确的field与返回值分开。

你不必抛出这些异常,但如果你不抛出,在错误路径上,你的程序会有未定义的行为。

Json::Value getField(int field,Json::Value root)
{
    auto it = std::find_if(root["properties"].begin(), root["properties"].end(),
        [field](Json::Value item){ return item["field"].toInt() == field }); 
    if (it = root["properties"].end())
    { throw std::runtime_error("missing field"); }
    return *it;
}
// Primary template defined but not declared
template<typename T> T getProperty(int field,Json::Value root);
template<> int getProperty(int field,Json::Value root)
{
    Json::Value value = getField(field, root);
    if (value["type"].asString() == "int") 
    { throw std::runtime_error("not an int"); }
    return value["currVal"].asInt();
}
template<> std::string getProperty(int field,Json::Value root)
{
    Json::Value value = getField(field, root);
    if (value["type"].asString() == "string") 
    { throw std::runtime_error("not a string"); }
    return value["currVal"].asString();
}
// etc