Search code examples
c++variant

How to convert variant to string in C++


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
}

Solution

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