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
For those (like me) who
here is another take:
#include
#include
template struct NonConst;
template struct NonConst {using type = T&;};
template struct NonConst {using type = T*;};
#define NON_CONST(func) \
template auto func(T&&... a) \
-> typename NonConst(a)...))>::type \
{ \
return const_cast(a)...))>( \
std::as_const(*this).func(std::forward(a)...)); \
}
It is basically a mix of the answers from @Pait, @DavidStone and @sh1 (EDIT: and an improvement from @cdhowie). What it adds to the table is that you get away with only one extra line of code which simply names the function (but no argument or return type duplication):
class X
{
const Z& get(size_t index) const { ... }
NON_CONST(get)
};
Note: gcc fails to compile this prior to 8.1, clang-5 and upwards as well as MSVC-19 are happy (according to the compiler explorer).