Sign in to follow this  
nife87

Templated operator! overloading

Recommended Posts

nife87    520
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
MaulingMonkey    1730
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
Shinkage    595
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this