Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert std::variant<int, string> to string

I have a std::variant<int, std::string>. Regardless of whether it's representing an int or string, I want to convert it to a string. The conversion from int to string is simply std::to_string(int).

Currently, I use:


get_if<int> int_ptr{&v};  // v is a std::variant<int, std::string> and we don't know before hand which it is

string res;
if (int_ptr == nullptr) {
  res = *get_if<string>{&v};
} else {
  res = to_string(*int_ptr);
}

Is there a shorter approach to this?

like image 682
24n8 Avatar asked Jun 20 '26 06:06

24n8


2 Answers

In C++20, you can use std::visit with std::format to do this

#include <variant>
#include <format>

int main() {
  std::variant<int, std::string> v{...};
  std::string res = std::visit([](const auto& arg) { return std::format("{}", arg); }, v);
}
like image 178
康桓瑋 Avatar answered Jun 21 '26 19:06

康桓瑋


The normal approach would be std::visit. Here's pseudocode off the top of my head

#include <string> //this has std::to_string(int)

const std::string& to_string(const std::string& s) {return s;}

...

using std::to_string;
std::string str = std::visit([](auto&& arg){return to_string(arg);}, v);
like image 29
Mooing Duck Avatar answered Jun 21 '26 19:06

Mooing Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!