我有一个
std::variant<int, std::string>
。不管它代表的是int还是字符串,我都想将它转换为字符串。从 int
到 string
的转换很简单 std::to_string(int)
。
目前,我使用:
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);
}
有没有更短的方法?
std::visit
。这是我脑海中浮现的伪代码
#include <string> //this has std::to_string(int)
const std::string& to_string(const std::string& s) {return s;}
...
std::string str = std::visit([](auto&& arg){return to_string(arg);}, v);