title: const_cast and std::move to remove constness from non-reference
body: <p>I have an external library which I can not modify. The library declares a template function that for some reason returns <code>const</code> non-reference object:</p>
  
  <pre><code>template&lt;class C&gt;
  const C foo();
  </code></pre>
  
  <p>I have another external library which I can not modify too. The library declares a class that is non-copyable and has a move constructor from a non-const object only:</p>
  
  <pre><code>struct bar {
      bar();
      bar(const bar&amp;)=delete;
      bar(bar&amp;&amp;);
  };
  </code></pre>
  
  <p>Now I need to use <code>foo&lt;bar&gt;</code>. A simple usage:</p>
  
  <pre><code>bar buz() {
      return foo&lt;bar&gt;();
  }
  </code></pre>
  
  <p>fails with </p>
  
  <blockquote>
  <pre><code>main.cpp: In function 'bar buz()':
  main.cpp:13:21: error: use of deleted function 'bar::bar(const bar&amp;)'
       return foo&lt;bar&gt;();
                       ^
  main.cpp:8:5: note: declared here
       bar(const bar&amp;)=delete;
       ^~~
  </code></pre>
  </blockquote>
  
  <p>which makes sense, and no simple workaround make the code compile.</p>
  
  <p>However, if I add some more complex workaround:</p>
  
  <pre><code>bar buz() {
      return const_cast&lt;bar&amp;&amp;&gt;(std::move(foo&lt;bar&gt;()));
  }
  </code></pre>
  
  <p>it compiles and the whole code work as expected (not only the simplified example above, but my real code too).</p>
  
  <p>However, it is safe, or am I running into some undefined behavior? Is there any better workaround?</p>
  
  <hr>
  
  <p>I have read and I understand questions about returning <code>const</code> from functions (<a href="https://stackoverflow.com/questions/6299967/what-are-the-use-cases-for-having-a-function-return-by-const-value-for-non-built">1</a>, <a href="https://stackoverflow.com/questions/12051012/should-i-return-const-objects">2</a>), and the common answer there seems to be that returning <code>const</code> objects is discouraged in modern C++, but my question is not about it, but about how can I workaround the situation when an external library returns <code>const</code> object.</p>