Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visit a variant with a monostate

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

like image 202
CD86 Avatar asked Oct 18 '25 06:10

CD86


1 Answers

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);
}
like image 55
quetzalcoatl Avatar answered Oct 19 '25 22:10

quetzalcoatl