• Advertisement
Sign in to follow this  

Templated operator! overloading

This topic is 2686 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm having a somewhat hard time figuring out why GCC won't accept this pointer check (operator!):

template<typename T> class P
{
public:
typedef boost::weak_ptr<T> Weak;
};

template<typename T> bool operator!(const typename P<T>::Weak &p)
{
return (!p.expired() && p.lock().get() != 0);
}

...

P<int>::Weak p;

if (!p) // error here!
dosomething();

GCC complains about "no match for 'operator!' in '!p'"?

Share this post


Link to post
Share on other sites
Advertisement
C++ compilers can only infer simple type expressions that don't involve dependant typenames. Why? Consider that if P were specialized, or the Weak typedef used a specialized class, P<int>::Weak and P<short>::Weak could be the same type.

Use template<typename T> bool operator!(const boost::weak_ptr<T> &p) instead. Or better yet: don't do this.

Quote:
Originally from Boost Documentation's weak_ptr Introduction
Compared to shared_ptr, weak_ptr provides a very limited subset of operations since accessing its stored pointer is often dangerous in multithreaded programs, and sometimes unsafe even within a single thread (that is, it may invoke undefined behavior.)


Note well that shared_ptr does provide operator! -- it's omission from weak_ptr is very intentional and by design!

Share this post


Link to post
Share on other sites
EDIT: Looking at your code more, it makes no sense. What are you trying to do with your custom negation operator? The way you have it written !p will return true if p is valid... which doesn't seem right...

Why not just do this?
if(!p.expired())
dosomething();

And the other way around, if 'p' is going to be used in dosomething, do this:
if(shared_ptr<...> tmp = p.lock()) {
dosomething();
}

This is really the only way not to end up with a disaster if you are working with more than one thread.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement