如何将 std::variant<int, string> 转换为字符串

问题描述 投票:0回答:1

我有一个

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

有没有更短的方法?

c++ string variant
1个回答
0
投票

正常的方法是

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);
© www.soinside.com 2019 - 2024. All rights reserved.