title: Using decltype to cast this to const
body: <p>I'm attempting to solve a problem in which <code>decltype</code> will greatly simplify things, but I'm running into an issue using <code>decltype</code> on <code>*this</code> and adding a <code>const</code> qualifier. The sample code below demonstrates the problem.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct Foo
  {
    void bar()
    {
      static_cast&lt;const decltype(*this)&amp;&gt;(*this).bar();
    }
  
    void bar() const
    {
      std::cout &lt;&lt; "bar" &lt;&lt; std::endl;
    }
  };
  
  int main(int argc, char* argv[])
  {
    Foo f;
    f.bar(); // calls non-const method
    return 0;
  }
  </code></pre>
  
  <p>The code compiles in MSVC2010, but execution recurses until a stack overflow occurs.</p>
  
  <p><a href="http://www.ideone.com/VflMt" rel="noreferrer">Ideone</a> reports compiler error</p>
  
  <pre><code>prog.cpp: In member function 'void Foo::bar()':
  prog.cpp:7:38: error: 'const' qualifiers cannot be applied to 'Foo&amp;'
  </code></pre>
  
  <p>If I change the line</p>
  
  <pre><code>static_cast&lt;const decltype(*this)&amp;&gt;(*this).bar();
  </code></pre>
  
  <p>to</p>
  
  <pre><code>static_cast&lt;const Foo&amp;&gt;(*this).bar();
  </code></pre>
  
  <p>it works as expected.</p>
  
  <p>Am I misusing or misunderstanding decltype?</p>