Æsir
Æsir

Reputation: 65

How to convert value of std::variant to std::string using std::visit

I want to convert value of std::variant to std::string, but this code doesn't work:

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*/);
}

I want to convert, for example, this: (in code) AnyType some = true; to (in console) true.

So, can somebody help me with this?

Upvotes: 2

Views: 1898

Answers (2)

Jamie Nicholl-Shelley
Jamie Nicholl-Shelley

Reputation: 679

I variation on @maxin's reply that I find a bit more self contained:

typedef std::variant<unsigned int, double, float, int> VariableData;
typedef std::tuple<unsigned int, VariableData> Variable;//UID, Data
struct VisitPrintVariable
{
   void operator()(unsigned int value) { std::cout << std::to_string(value); }
   void operator()(double value) { std::cout << std::to_string(value); }
   void operator()(float value) { std::cout << std::to_string(value); }
};

static void PrintVariable(VariableData& vd)
{
    std::visit(VisitPrintVariable(), vd);
}

Upvotes: -1

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136525

A working example:

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<...>> as one of std::variant<...> members requires using a recursive variant type, which is not supported by std::variant, but supported by boost::variant.

Upvotes: 5

Related Questions