Re: Operator ->* in smart pointers
* Dario Saccavino:
It seems to me that operator->* is overloadable in C++ (just like
operator->), and it should be useful to implement in smart pointer
classes.
However, I haven't found its implementation either in the standard
weak_ptr class, or in any boost smart pointer. Was it intentionally
left out of those headers?
Actually there's a workaround: just write
(ptr.operator->())->*memptr
instead of
ptr->*memptr
But it looks very ugly. How am I supposed to use member pointers with
smart pointers?
In general it's not a good idea to use member pointers.
They're tricky and yield unmaintainable code, they can circumvent access
control, and mostly they indicate design errors. Regard member pointers
as being in the same class of constructs as goto. Sometimes a necessary
evil, but not something you'd employ without due consideration.
If you absolutely must, try something like
#include <iostream>
#include <boost/shared_ptr.hpp>
struct Foo
{
int value;
Foo( int x = 42 ): value( x ) {};
};
template< typename Result, typename SmartPtr, typename Class >
Result& operator->*( SmartPtr& p, Result Class::* pMember )
{
return (&*p)->*pMember; // Not guaranteed there is get().
}
int main()
{
boost::shared_ptr<Foo> p( new Foo );
int Foo::* pFooInt = &Foo::value;
p->*pFooInt = 43;
std::cout << p->value << std::endl;
}
Note that to be general, the operator's result type must be adjusted to
the union of the cv-qualification of the two arguments.
And that's non-trivial.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?