Let\'s say I have the following class X where I want to return access to an internal member:
class Z
{
// details
};
class X
{
std::vec
C++17 has updated the best answer for this question:
T const & f() const {
return something_complicated();
}
T & f() {
return const_cast(std::as_const(*this).f());
}
This has the advantages that it:
volatile by accident, but volatile is a rare qualifier)If you want to go the full deduction route then that can be accomplished by having a helper function
template
constexpr T & as_mutable(T const & value) noexcept {
return const_cast(value);
}
template
constexpr T * as_mutable(T const * value) noexcept {
return const_cast(value);
}
template
constexpr T * as_mutable(T * value) noexcept {
return value;
}
template
void as_mutable(T const &&) = delete;
Now you can't even mess up volatile, and the usage looks like
decltype(auto) f() const {
return something_complicated();
}
decltype(auto) f() {
return as_mutable(std::as_const(*this).f());
}