C ++中的std :: variant cout

埃德维姆

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

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

考虑中

#include <iostream>
#include <variant>
#include <string>
using namespace std;
int main() {

    variant<int, string> a = "Hello";
    cout<<a;
}

我无法打印输出。有什么简短的方法吗?提前非常感谢您。

金善达

采用 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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章