A less verbose const_cast Motivation

const_cast is a beast that I seldomly encounter. But when I do so it is mostly a bad experience.

Nobody knows what most of the C++ programmers do but so far I only ever had one use for const_cast: to cast away a const from a type. For this task const_cast is too verbose:

const std::vector&lt;int&gt; constVectorOfInts = {/*...*/};
// never do this in real code!
auto &amp;mutableVectorOfInts = const_cast&lt;std::vector&lt;int&gt;&gt;(constVectorOfInts);


IMHO, there is no gain in readability when repeating the type.

Enter my proposal:

unconst_cast

We can write a template function unconst_cast that solves only the problem of removing const.

/**
 * @brief Returns a mutable reference to the same object
 */
template &lt;class T&gt; T &amp;unconst_cast(const T &amp;v) { return const_cast&lt;T &amp;&gt;(v); }

/**
 * @brief Returns a mutable pointer to the same object
 */
template &lt;class T&gt; T *unconst_cast(const T *v) { return const_cast&lt;T *&gt;(v); }

int main() {
  int i;
  const int *constPointerToI = &amp;i;
  int *unconstPointerToI = unconst_cast(constPointerToI);
  unconstPointerToI = unconst_cast(&amp;i);
  int &amp;unconstReferenceToI = unconst_cast(*constPointerToI);
  int &amp;unconstReferenceToI2 = unconst_cast(i);
}


Our code from above would become:

auto &amp;mutableVectorOfInts = unconst_cast(constVectorOfInts);


Other pros:


can overload for other types (in contrast to const_cast), e.g. for own iterators (mutableIterator = unconst_cast(constIterator))
we find usages when string searching for "const_cast"


Review Goals


Is this a bad idea? 
Is my implementation correct?
Is the naming alright/understandable?
•Is this a bad idea? 


It is unnecessary.


  Nobody knows what most of the C++ programmers do but so far I only ever had one use for const_cast: to cast away a const from a type.


You can also use it to partially take away constness:

int do_things(const char* p);

const char* const xyz = "abc";
do_things( const_cast&lt;const char*&gt;(xyz) );


The gain in readability comes from the result type being explicitly specified.

If you have APIs that only work for non-const pointers when they should work for const (this is the most legitimate use for const_cast) you should wrap them and centralize/localize/hide the call to const_cast.

If you find yourself writing const_cast calls again and again, the problem is not poor readability of the code, but bad API design.