title: Can an object know its own constness?
body: <p>With <code>decltype</code> and <code>std::is_const</code> the constness of a variable can be externally detected. <strong>But is it also possible for an object to know its own constness?</strong> Usage should be like:</p>
  
  <pre><code>#include &lt;type_traits&gt;
  #include &lt;iostream&gt;
  #include &lt;ios&gt;
  
  struct Test
  {
      Test() {}
  
      bool print() const
      {
         // does not work as is explained in https://stackoverflow.com/q/9890218/819272
         return std::is_const&lt;decltype(*this)&gt;::value; // &lt;--- what will work??
      }
  };
  
  int main()
  {
      Test t;
      const Test s;
  
      // external constness test
      std::cout &lt;&lt; std::boolalpha &lt;&lt; std::is_const&lt;decltype(t)&gt;::value &lt;&lt; "\n";
      std::cout &lt;&lt; std::boolalpha &lt;&lt; std::is_const&lt;decltype(s)&gt;::value &lt;&lt; "\n";
  
      // internal constness test
      std::cout &lt;&lt; std::boolalpha &lt;&lt; t.print() &lt;&lt; "\n";
      std::cout &lt;&lt; std::boolalpha &lt;&lt; s.print() &lt;&lt; "\n"; // &lt;--- false??
  }
  </code></pre>
  
  <p>Output on <a href="http://liveworkspace.org/code/2HfkHT$35" rel="nofollow noreferrer">LiveWorkSpace</a> Is this somehow possible?</p>
  
  <p><strong>MOTIVATION</strong>: I want to be able to detect whether a const member function is invoked on a const object or is coming from a non-const object. The object could e.g. represent a cache and the member a view. If the cache was const, one could presumably use an optimized draw routine, whereas if the underlying data was non-const, the draw routine would need to do periodically check if the data was refreshed.</p>
  
  <p><strong>NOTE</strong>: the related <a href="https://stackoverflow.com/q/9890218/819272">question</a> asks how to break the build for const objects, but I don't quite understand if the answer to that implies a definite NO for my question. If not, I want to capture the constness in a boolean for further usage. </p>
  
  <p><strong>EDIT</strong>: as was pointed out @DanielFrey, the constructor is not a good place to test for constness. What about a const member function?</p>
  
  <hr>
  
  <p><strong>UPDATE</strong>: Thanks everyone for correcting my initially ill-posed question and providing the various parts of the answer (constructors' ill-defined constness, rvaluedness of <code>this</code>, the contextual meaning of <code>const</code>, the -with hindsight- obvious overload trick that I had overlooked, and the const reference aliasing loophole lurking in the shadows). For me this question was Stackoverflow at its best. I decided to select @JonathanWakely's answer because it showed how to define <code>Mutable</code> and <code>Immutable</code> classes that strengthen the constness concept to achieve what I want in a foolproof way.</p>