I have tried every snippet I can find on streaming the contents of a variant but nothing seems to work in my particular use case:
Given a variant of the form std::variant<int,std::pair<char, char>> myVar
how can one go about streaming the contents of myVar
without explicitly knowing what myVar
contains.
For example:
#include <iostream>
#include <variant>
typedef std::variant<int,std::pair<char, char>> myVar;
template <typename T>
std::ostream& operator<<(std::ostream& os, std::pair<T, T> &p) {
os << "(" << p.first << ", " << p.second << ")";
return os;
} // This is so we can stream a pair...
/*
...black box to stream variant here...
*/
std::pair<char, char> testPair = {'X','a'};
int testInt = 5;
myVar testVariant = testInt;
std::cout << testVariant << "\n" // Should print 5.
testVariant = testPair;
std::cout << testVariant << "\n" // Should print (X, a).
Any snippet I use for streaming variants, for example
template<typename T, typename... Ts>
std::ostream& operator<<(std::ostream& os, const std::variant<T, Ts...>& v)
{
std::visit([&os](auto&& arg) {
os << arg;
}, v);
return os;
}
It fails in this case and returned the following error message:
"Invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'const std::__1::pair<char, char>')"
error --- no matter what I try this is all I ever get!
I cannot figure out what is wrong with this code. Please can somebody help me to identify and solve the issue here?
3rd party libraries such as boost are an absolute no-go.