title: How to implement static virtual member function
body: <p><strong>TL/DR: Is there a (more convenient) way to implement such functionality?</strong></p>
  
  <p>I have to invoke the same static code for both class-type and class-instance represented by reference to base:</p>
  
  <pre><code>int main()
  {
      // Invokes on class
      bar&lt;C1&gt;(); // invokes C1::foo()
      bar&lt;C2&gt;(); // invokes C2::foo()
  
      // Invokes on instance
      bar(C1()); // invokes C1::foo()
      bar(C2()); // invokes C2::foo()
  }
  </code></pre>
  
  <p>But the problem is that I can't implement that without some code duplication. For each derived class I have to write both static and virtual methods. Static - because I can't invoke a virtual method on class, and virtual, which calls static - because there's no way to distinguish object behaviour except by virtual methods:</p>
  
  <pre><code>template&lt;typename T&gt;
  void bar()
  {
      T::foo();
  }
  
  void bar(A const &amp;r)
  {
      r.foo();
  }
  </code></pre>
  
  <p>Thus, my workaround to solve the problem of duplicating code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  class A
  {
  public:
      virtual void foo() const = 0;
  };
  
  template&lt;typename derived_T&gt;
  class B: public A
  {
  public:
      virtual void foo() const
      {
          derived_T::foo();
      }
  };
  
  class C1 : public B&lt;C1&gt;
  {
  public:
      static void foo()
      {
          std::cout &lt;&lt; "C1::foo()" &lt;&lt; std::endl;
      }
  };
  
  class C2 : public B&lt;C2&gt;
  {
  public:
      static void foo()
      {
          std::cout &lt;&lt; "C2::foo()" &lt;&lt; std::endl;
      }
  };
  </code></pre>
  
  <p>This approach works perfectly, but it has at least two inconveniences.</p>
  
  <p>Firstly, I had to introduce an auxiliary template class B with implemented virtual method.</p>
  
  <p>Secondly, every inheritance chain (from B to final class) must consists of templates that makes impossible using any intermediate class as pointer/reference type. eg. A &lt;- B &lt;- T1 &lt;- T2 &lt;- C , T1 and T2 must be template classes to provide C::foo().</p>