函数根据输入返回不同的类型
Function to return different types based on input
我想写一个函数,根据一些条件返回String
、Int
、Float
。使用C11。尝试了一些已经提到的东西,不适用于template/auto。如果函数只有一个返回,那么它现在很好。当我添加另一个返回字符串时,编译错误。错误:从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;
}
}
}
}
如果您使用的是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
相关文章:
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么要为指针返回类型返回一系列字符?
- 有没有办法根据运行时值的类型返回 constexpr 对象
- 从弱指针返回类型返回共享指针
- 无法为unique_ptr返回类型返回 nullptr
- 为什么双重类型返回无穷大
- std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
- C 策略设计具有可变类型返回值
- 根据类型返回一个值
- 在C++中,将double转换为long的类型返回了不正确的值
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 具有引用类型返回的函数
- C++ 如何使模板<T>f() 为整数 T 返回 -1,为指针类型返回 nullptr
- C++模板:按类型返回值
- 以Integer返回类型返回浮点值
- 使用 C++14 的自动功能类型返回扣除代替 std::common_type 是否始终安全?
- 为什么允许新运算符向每个指针类型返回*void
- 适当的函数返回类型返回日期时间
- c++中布尔类型返回函数的默认返回值
- 在c#中使用非托管c++代码对所有double类型返回0