edv*_*lme 3 c++ operator-overloading variant
我对 CPP 比较陌生,最近偶然发现std::variant了 C++17。
但是,我无法<<在此类数据上使用运算符。
考虑
#include <iostream>
#include <variant>
#include <string>
using namespace std;
int main() {
variant<int, string> a = "Hello";
cout<<a;
}
Run Code Online (Sandbox Code Playgroud)
我无法打印输出。有没有什么简短的方法可以做到这一点?非常感谢你。
您可以使用std::visit,如果你不想使用std::get。
#include <iostream>
#include <variant>
struct make_string_functor {
std::string operator()(const std::string &x) const { return x; }
std::string operator()(int x) const { return std::to_string(x); }
};
int main() {
const std::variant<int, std::string> v = "hello";
// option 1
std::cout << std::visit(make_string_functor(), v) << "\n";
// option 2
std::visit([](const auto &x) { std::cout << x; }, v);
std::cout << "\n";
}
Run Code Online (Sandbox Code Playgroud)
用 std::get
#include <iostream>
#include <variant>
#include <string>
using namespace std;
int main() {
variant<int, string> a = "Hello";
cout << std::get<string>(a);
}
Run Code Online (Sandbox Code Playgroud)
如果要自动获取,不知道它的类型是做不到的。也许你可以试试这个。
string s = "Hello";
variant<int, string> a = s;
cout << std::get<decltype(s)>(a);
Run Code Online (Sandbox Code Playgroud)