title: C++ template to cover const and non-const method
body: <p>I have a problem with duplication of identical code for <code>const</code> and non-<code>const</code> versions.  I can illustrate the problem with some code.  Here are two sample visitors, one which modifies the visited objects and one which does not.</p>
  
  <pre><code>struct VisitorRead 
  {
      template &lt;class T&gt;
      void operator()(T &amp;t) { std::cin &gt;&gt; t; }
  };
  
  struct VisitorWrite 
  {
      template &lt;class T&gt; 
      void operator()(const T &amp;t) { std::cout &lt;&lt; t &lt;&lt; "\n"; }
  };
  </code></pre>
  
  <p>Now here is an aggregate object - this has just two data members but my actual code is much more complex:</p>
  
  <pre><code>struct Aggregate
  {
      int i;
      double d;
  
      template &lt;class Visitor&gt;
      void operator()(Visitor &amp;v)
      {
          v(i);
          v(d);
      }
      template &lt;class Visitor&gt;
      void operator()(Visitor &amp;v) const
      {
          v(i);
          v(d);
      }
  };
  </code></pre>
  
  <p>And a function to demonstrate the above:</p>
  
  <pre><code>static void test()
  {
      Aggregate a;
      a(VisitorRead());
      const Aggregate b(a);
      b(VisitorWrite());
  }
  </code></pre>
  
  <p>Now, the problem here is the duplication of <code>Aggregate::operator()</code> for <code>const</code> and non-<code>const</code> versions.</p>
  
  <p>Is it somehow possible to avoid duplication of this code?</p>
  
  <p>I have one solution which is this:</p>
  
  <pre><code>template &lt;class Visitor, class Struct&gt;
  void visit(Visitor &amp;v, Struct &amp;s) 
  {
      v(s.i);
      v(s.i);
  }
  
  static void test2()
  {
      Aggregate a;
      visit(VisitorRead(), a);
      const Aggregate b(a);
      visit(VisitorWrite(), b);
  }
  </code></pre>
  
  <p>This means neither <code>Aggregate::operator()</code> is needed and there is no duplication.  But I am not comfortable with the fact that <code>visit()</code> is generic with no mention of type <code>Aggregate</code>.  </p>
  
  <p>Is there a better way?</p>