Search code examples
c++operator-overloadingvariant

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.


Solution

  • 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);