How to convert variant to string in C++

Viewed 609

I'm new in C++, and I wanted to know how to convert a variant to string:

variant<string, int, float> value;

if (!value.empty()) {
   // do something
}
5 Answers

Well, you will need custom code for the different cases... The following function would do as you want:

string stringify(variant<string, int, float> const& value) {
    if(int const* pval = std::get_if<int>(&value))
      return to_string(*pval);
     
    if(float const* pval = std::get_if<float>(&value))
      return to_string(*pval);
    
    return get<string>(value);
}

you can use std::holds_alternative method to check if the value is a string, and then std::get to retrieve it:

if (std::holds_alternative<std::string>(value)) {
    std::cout << std::get<std::string>(value);
}

To extract the object of type T from a std::variant:

std::variant<T, T1, T2> myVariant;

try
{
    auto& myT = std::get<T>(myVariant);
}
catch (std::bad_variant_access const& ex)
{
    ...
}

The try-catch is only necessary if you try to get a type that doesn't exist in the variant. Alternatively, you can check if an object of that type is contained in the variant, with std::holds_alternative.

you can extract it either by index or by type and both will throw an exception if it is not the current active index or type

// by index
auto& str = std::get<0>(value);
// by type
auto& str = std::get<string>(value);

to check if the variant is holding a string you can check by index or type

// by index
bool is_str = value.index() == 0;
// by value
bool is_str = std::holds_alternative<string>(value);

std::visit is the preferred way to work with std::variant, you might do something like:

std::string to_string(std::variant<std::string, int, float> var)
{
    return std::visit([]<typename T>(const T& e){
        if constexpr (std::is_same_v<T, std::string>) {
            return e;
        } else { // float/int
            return std::to_string(e);
        }
    }, var);
}

Demo

Related