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?
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);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With