首页 > 解决方案 > 如何使用 std::visit 将 std::variant 的值转换为 std::string

问题描述

我想将值转换std::variantstd::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

那么,有人可以帮我解决这个问题吗?

标签: c++stlc++17std

解决方案


一个工作示例:

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.


推荐阅读