Home > OS >  How to convert variant to string in C
How to convert variant to string in C

Time:12-10

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
}

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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);
  • Related