I am having trouble wrapping my head around variant.
I read, that I can use std::monostate to imply an empty state as one of the alternatives inside the variant. However, how do I then use the visitor pattern that is facilitated with std::visit?
#include <variant>
struct Visitor{
void operator()(double){};
void operator()(int){};
};
int main() {
std::variant<std::monostate, int, double> v = 1;
std::visit(Visitor{}, v);
}
does not work and neither does providing an call-operator overload for std::monostate .
If I try to include a universal reference overload for the call operator, it just matches everything and does not use the two specific overloads anymore
I added proper visitor method and it works for me on https://wandbox.org/ c++2a
What was your problem with it?
#include <iostream>
#include <variant>
struct Visitor{
void operator()(double){ std::cout << "Double!" << std::endl; };
void operator()(int){ std::cout << "Int!" << std::endl; };
// that was missing:
void operator()(std::monostate){ std::cout << "Mono!" << std::endl; };
};
int main() {
std::variant<std::monostate, int, double> v = 1;
std::variant<std::monostate, int, double> w;
std::visit(Visitor{}, v);
std::visit(Visitor{}, w);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With