Sign in to follow this  
Storyyeller

c++ template overloading help

Recommended Posts

Storyyeller    215
I am trying to create a template function which works on regular pointers, shared pointers, and weak pointers and returns the result of calling Active() on the pointed to object.

However, I can't figure out how to do it. It seems like it should be unambiguous because only the shared pointer has the -> operator, and only the weak pointer has the lock() function, but I can't get it to work.

When I try this it says there is a multiple definition error.


template <class T>
bool checkPtrActive(T sptr)
{
return sptr->Active();
}

template <class T>
bool checkPtrActive(T wptr)
{
auto sptr = wptr.lock();
return sptr && sptr->Active();
}



Share this post


Link to post
Share on other sites
MagForceSeven    514
Your problem is that templates can't use the body of the function to disambiguate the type. They can only use the function parameter types and in your example they are identical.

I don't know what implementation of shared/weak pointers you're using, but assuming that they're templated types I expect what you want is something like:


template <class T>
bool checkPtrActive(const shared_pointer<T> &sptr)
{
//do shared pointer stuff here
}

template <class T>
bool checkPtrActive(const weak_pointer<T> &wptr)
{
//do weak pointer stuff here
}


Share this post


Link to post
Share on other sites
parish    100
The c++ function templates overloading can also be mixed with normal c++ functions. The following function signature can also be mixed with the above code and this will also be used by the C++ compiler while resolving function calls.

int min(int fParam1,int fParam2)
{

cout << "Normal function called for "<< fParam1 << " " <<fParam2 <<endl;

if(fParam1 < fParam2)
return fParam1;
else
return fParam2;
}

MOD EDIT: Removed irrelevant spammy link

[Edited by - Evil Steve on October 13, 2010 5:30:59 AM]

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