我想将 的值转换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*/);
}
Run Code Online (Sandbox Code Playgroud)
例如,我想将这个: (在代码中) 转换AnyType some = true;
为 (在控制台中) 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);
}
Run Code Online (Sandbox Code Playgroud)
std::vector<std::variant<...>>
作为成员之一std::variant<...>
需要使用递归变体类型,该类型不受 的支持std::variant
,但受 的支持boost::variant
。
归档时间: |
|
查看次数: |
1748 次 |
最近记录: |