c++ - 如何使用 std::visit 将 std::variant 的值转换为 std::string
问题描述
我想将值转换std::variant
为std::string
,但这段代码不起作用:
using AnyType = std::variant <bool, char, integer, double, std::string, std::vector <AnyType>/*, Object, Extern, InFile*/>;
struct AnyGet {
AnyGet() {}
std::string operator()(std::string& result, const bool& _ctx) { return _ctx ? "true" : "false"; }
std::string operator()(std::string& result, const char& _ctx) { return std::string(1, _ctx); }
std::string operator()(std::string& result, const integer& _ctx) { return std::to_string(_ctx); }
std::string operator()(std::string& result, const double& _ctx) { return std::to_string(_ctx); }
std::string operator()(std::string& result, const std::string& _ctx) { return _ctx; }
std::string operator()(const std::vector <AnyType>& _ctx, const std::string& _nl = "\n") {/*This depends on to_string*/}
};
std::string to_string(const AnyType& _input, const std::string& _new_line){
std::visit(/*I don't know, what I must write here*/);
}
例如,我想将: (in code)AnyType some = true;
转换为 (in console) true
。
那么,有人可以帮我解决这个问题吗?
解决方案
一个工作示例:
using AnyType = std::variant<bool, char, int, double, std::string>;
struct AnyGet {
std::string operator()(bool value) { return value ? "true" : "false"; }
std::string operator()(char value) { return std::string(1, value); }
std::string operator()(int value) { return std::to_string(value); }
std::string operator()(double value) { return std::to_string(value); }
std::string operator()(const std::string& value) { return value; }
};
std::string to_string(const AnyType& input) {
return std::visit(AnyGet{}, input);
}
std::vector<std::variant<...>>
作为std::variant<...>
成员之一,需要使用递归变体类型,它不受 支持std::variant
,但受boost::variant
.
推荐阅读
- django - 通过模板执行视图后,Django 视图无法正确呈现
- r - R to MySQL 抛出错误“无法运行语句:无效的 utf8mb4 字符串”
- c# - 不等待 Async 方法,该方法又在其中等待
- javascript - 滑块菜单使外部元素不可点击
- c++ - 在 cmake3 上指定临时构建文件路径
- azure - 导出所有 Azure AD 组及其成员 (PowerShell)
- json - VBA JsonConverter 添加额外的引号
- python - Matplotlib - 让颜色条与绘图中的颜色对齐并使用原始值作为标签
- r - 低于阈值的值的百分比(按年份)
- python - 在 Python 中读取 swagger 文件