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<int> constVectorOfInts = {/*...*/};
// never do this in real code!
auto &mutableVectorOfInts = const_cast<std::vector<int>>(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 <class T> T &unconst_cast(const T &v) { return const_cast<T &>(v); }
/**
* @brief Returns a mutable pointer to the same object
*/
template <class T> T *unconst_cast(const T *v) { return const_cast<T *>(v); }
int main() {
int i;
const int *constPointerToI = &i;
int *unconstPointerToI = unconst_cast(constPointerToI);
unconstPointerToI = unconst_cast(&i);
int &unconstReferenceToI = unconst_cast(*constPointerToI);
int &unconstReferenceToI2 = unconst_cast(i);
}
Our code from above would become:
auto &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?