G
Gennaro Prota
Hi,
I've been having this facility for a long while in my personal
toolset. I thought of it and then never used it.
template< typename C, typename Ret >
Ret &
forward_to_const(
Ret const & ( C::* p )() const,
C const & inst )
{
return const_cast< Ret & >( ( inst.*p )() ) ;
}
It would be used more or less like this:
class C
{
int m ;
public:
...
int const &
f() const
{
return m ;
}
int &
f()
{
#ifdef IMPL_MANUALLY
C const & me( *this ) ;
return const_cast< int & >( me.f() ) ;
#else
return forward_to_const( &C::f, *this ) ;
#endif
}
} ;
I know, of course, that it doesn't handle functions with
parameters, functions returning pointers or even non-member
functions. It isn't meant to be so much general. My question is
rather whether you think it's worth anything or just adds
clutter to the code. The initial motivation was that I didn't
want to think about the add-const/remove-const manouvre each
time I needed such two "twin" member functions, especially since
it doesn't happen often, so the thinking process is a tad
longer. But, having just encountered a case where I need the
twin overloads, I'm not seeing a clear advantage of using this
forward_to_const stuff.
I've been having this facility for a long while in my personal
toolset. I thought of it and then never used it.
template< typename C, typename Ret >
Ret &
forward_to_const(
Ret const & ( C::* p )() const,
C const & inst )
{
return const_cast< Ret & >( ( inst.*p )() ) ;
}
It would be used more or less like this:
class C
{
int m ;
public:
...
int const &
f() const
{
return m ;
}
int &
f()
{
#ifdef IMPL_MANUALLY
C const & me( *this ) ;
return const_cast< int & >( me.f() ) ;
#else
return forward_to_const( &C::f, *this ) ;
#endif
}
} ;
I know, of course, that it doesn't handle functions with
parameters, functions returning pointers or even non-member
functions. It isn't meant to be so much general. My question is
rather whether you think it's worth anything or just adds
clutter to the code. The initial motivation was that I didn't
want to think about the add-const/remove-const manouvre each
time I needed such two "twin" member functions, especially since
it doesn't happen often, so the thinking process is a tad
longer. But, having just encountered a case where I need the
twin overloads, I'm not seeing a clear advantage of using this
forward_to_const stuff.