标准::C++中的变体

std::variant cout in C++

本文关键字:C++ 标准      更新时间:2023-10-16

我对CPP相对较新,最近偶然发现了C++17std::variant

但是,我无法对此类数据使用<<运算符。

考虑到

#include <iostream>
#include <variant>
#include <string>
using namespace std;
int main() {
variant<int, string> a = "Hello";
cout<<a;
}

我无法打印输出。有什么简短的方法可以做到这一点吗?提前非常感谢你。

如果您不想使用std::get,可以使用std::visit

#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";
}

使用std::get

#include <iostream>
#include <variant>
#include <string>
using namespace std;
int main() {
variant<int, string> a = "Hello";
cout << std::get<string>(a);
}

如果你想自动获取,在不知道其类型的情况下无法完成。也许你可以试试这个。

string s = "Hello";
variant<int, string> a = s;
cout << std::get<decltype(s)>(a);
#include <iostream>
#include <variant>
#include <string>
int main( )
{
std::variant<int, std::string> variant = "Hello";
std::string string_1 = std::get<std::string>( variant ); // get value by type
std::string string_2 = std::get<1>( variant ); // get value by index
std::cout << string_1 << std::endl;
std::cout << string_2 << std::endl;
//may throw exception if index is specified wrong or type
//Throws std::bad_variant_access on errors
//there is also one way to take value std::visit
}

这是描述链接:https://en.cppreference.com/w/cpp/utility/variant