繁体   English   中英

C++ 中的 std::variant cout

[英]std::variant cout in C++

我对 CPP 比较陌生,最近偶然发现了 C++17 的std::variant

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

考虑到

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

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

我无法打印 output。 有没有什么捷径可以做到这一点? 非常感谢你。

如果您不想使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM