Std: :Variant Cout in C++

Std: :Variant Cout in C++

I am relatively new to CPP and have recently stumbled upon std::variant for C++17.

However, I am unable to use the << operator on such type of data.

Considering

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

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

I am unable to print the output. Is there any short way of doing this? Thank you so much in advance.

3 Answers

You can use std::visit if you don't want to use 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";
}

use std::get

#include <iostream>
#include <variant>
#include <string>
using namespace std;

int main() {

    variant<int, string> a = "Hello";
    cout << std::get<string>(a);
}

If you want to get automatically, it can't be done without knowing its type. Maybe you can try this.

string s = "Hello";
variant<int, string> a = s;

cout << std::get<decltype(s)>(a);
4
#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
}

Here is the description link:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.