Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 432
edvilme Avatar asked Dec 02 '22 09:12

edvilme


1 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";
}
like image 66
Bill Lynch Avatar answered Dec 04 '22 03:12

Bill Lynch