• Advertisement
Sign in to follow this  

c++ template overloading help

This topic is 2687 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 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
Advertisement
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
Quote:
Original post by MagForceSeven
They can only use the function parameter types and in your example they are identical.


Notice though the SFINAE-principle, which sometimes helps to "overload" on quite complex (actually turing complete) conditions using some form of type traits and things like enable_if.

Share this post


Link to post
Share on other sites
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
Quote:
Original post by parish
...
Good job at googling "c++ template overloading help" there.

Share this post


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

  • Advertisement