[std :: C ++中的变量cout

问题描述 投票:1回答:3

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

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

正在考虑

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

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

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

c++ operator-overloading variant
3个回答
2
投票

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

5
投票

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

2
投票
#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

© www.soinside.com 2019 - 2024. All rights reserved.