c++ - C++ 函数返回不同的类型
问题描述
我试图创建一个函数,该函数根据参数返回值,如下所示:
type getValue(string input) return <OUTPUT>
OUTPUT
的类型将根据输入的内容更改为int
, string
,bool
等。我得到了排序,但我一直遇到的问题是返回类型。我试过auto
type 但我得到的只是这个错误:
错误:'auto' 的推导不一致:'int' 然后是 'char'
一遍又一遍地使用此函数可以输出的每种类型。我不会做模板,因为你必须这样做
getValue<type>(input);
而且我无法猜测输出以放入模板类型。我已经使用了很多我可以做的选项,但它太复杂了。
解决方案
正如评论所指出的,您需要使用std::variant
orstd::any
作为返回类型。
std::any getValue(string input) {
if (input == ...) {
return "string return type";
}
if (input == ...) {
return 100;
}
if (input == ...) {
return 123.456;
}
return false;
}
但是,如果您只能生成一小组返回类型,请考虑使用变体,因为它会受到更多限制:
// assuming these are the only 4 types you can return
using getValueReturnType = std::variant<std::string, int, double, bool>;
// The function definition would be exactly the same as above with std::any
getValueReturnType getValue(string input);
推荐阅读
- mysql - 如何为多个 Inner Join 编写 SQL 查询?
- scala - Circe:返回密封特征 (ADT) 的特定对象的通用函数
- jquery - 如何将 Fomantic-UI 导入 Angular 项目
- python - 将 Spacy 训练数据格式转换为 Spacy CLI 格式(用于空白 NER)
- c++ - 如何为文本 rpg 库存创建添加项目功能?
- c# - 带有动画 xamarin 表单的 ScrollView
- python - 用机会滚动轮盘赌并计算多次滚动的最大同侧序列
- php - 使用 html 按钮运行 shell 脚本
- sql - 如何将 nvarchar 转换为 uniqueidentifer?
- snowflake-cloud-data-platform - 无法使用 snowsql 连接到雪花数据库