c++ template overloading help

Started by
3 comments, last by Evil Steve 13 years, 6 months ago
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();    }
I trust exceptions about as far as I can throw them.
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}

--Russell Aasland
--Lead Gameplay Engineer
--Firaxis Games

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.

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]
Quote:Original post by parish
...
Good job at googling "c++ template overloading help" there.

This topic is closed to new replies.

Advertisement