title: C++ Visitor Pattern overload
body: <p>I have spent the past hours trying to find an elegant solution but however i am unable to. </p>
  
  <p>Description: I would like to have a default implementation for a visitor functor in class visitor_base_all and then each of the derived classes for example visitor_override would define the method just for what it needs. I understand that this does not work because the operator() is not passed to the derived classes (due to C++ not overload across scopes which is fair enough), so the question is how to do this exactly?
  I was thinking of doing it with overloaded lambdas or having a switch in the virtual base_class method and then each derived class overloading only the virtual methods called in that switch.</p>
  
  <p>Regarding the lambdas, I am not sure on how to do it.
  I have read the following before: <a href="https://pabloariasal.github.io/2018/06/26/std-variant/" rel="nofollow noreferrer">pablo_arias</a> <a href="https://arne-mertz.de/2018/05/overload-build-a-variant-visitor-on-the-fly/" rel="nofollow noreferrer">arne-mertz</a> and <a href="https://stackoverflow.com/questions/47383563/is-there-any-hope-to-call-a-common-base-class-method-on-a-stdvariant-efficient">stack_overflow_question</a> but i am still a bit confused on what would be the proper correct way forward.</p>
  
  <p>Thank you for your time</p>
  
  <p><strong>Short question:</strong> Proper c++17 way of making below compile/work. What is the proper way to generalize it for a big number of derived types in the variant and derived classes?</p>
  
  <p><strong>(Post comments-edit)</strong> My problem is more generalized for a big number of classes and a lot more types, so if possible i would prefer to template/generalize it somehow. Below is the example with just 1 derived class, but what would be a proper way with having 10 classes? (I wouldn't want to declare using in each of them if it can be avoided).</p>
  
  <pre><code>#include &lt;variant&gt;
  
  struct A{};
  struct B{};
  struct C{};
  using type_x = std::variant&lt;A,B,C&gt;;
  
  class base_class
  {
  protected:
      struct visitor_base_all
      {
          void operator()(const A&amp; a){std::cout&lt;&lt;"A_base" &lt;&lt; std::endl;}
          void operator()(const B&amp; b){std::cout&lt;&lt;"B_base" &lt;&lt; std::endl;}
          void operator()(const C&amp; c){std::cout&lt;&lt;"C_base" &lt;&lt; std::endl;}
      };
      virtual void run(type_x evt){return std::visit(visitor_base_all{}, evt);}
  };
  
  class derived_class :public base_class
  {
      struct visitor_override : public visitor_base_all
      {
          void operator()(const C&amp; c){};
      };
       virtual void run(type_x evt){return std::visit(visitor_override{}, evt);}
  };
  </code></pre>