6

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.

edvilme
  • 570
  • 7
  • 16

3 Answers3

15

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";
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
6

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);
김선달
  • 1,485
  • 9
  • 23
  • Ohhh, thx a lot. Is there by any chance any means of doing this automatically?. Like if `a` changes value along the program to become `4` instead of `"Hello"`? – edvilme Jun 13 '20 at 04:49
  • 1
    @edvilme No, there isn't any standard of getting value automatically. – 김선달 Jun 13 '20 at 04:53
  • Oh, that's unfortunate. Well thanks a lot anyways. :D – edvilme Jun 13 '20 at 04:55
  • @edvilme check @bill-lynch's reply at the bottom, using `std::visit` will work with any type that for which an overload of the `operator<<` is found – David Wright May 16 '22 at 09:10
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
}

Here is the description link: https://en.cppreference.com/w/cpp/utility/variant