std::variant C++ 中的 cout

std::variant cout in C++

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

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

考虑

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

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

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

使用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
}

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

不想用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";
}