Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ Moderated > Re: std::sort a...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 1 Topic 9279 of 9971
Post > Topic >>

Re: std::sort and overloaded compare function

by Geert-Jan Giezeman <geert@[EMAIL PROTECTED] > Feb 11, 2008 at 10:27 AM

michael.alexeev@[EMAIL PROTECTED]
 wrote:
> Hi All,
> 
> Consider the following simple program:
> 
> <code>
...snipped
> </code>
> 
> Both g++ (4.0.2) and Comeau on-line reject it with the following
> message:
> no instance of overloaded function "std::sort"
>            matches the argument list
>              The argument types that you used are: (Point2 *, Point2 *,
> <unknown-type>)
>      std::sort(array.begin(), array.end(), comparePoints);
> 
> If the second comparePoints function (1) is commented out or line (2)
> is modified to look like
>    std::sort(array.begin(), array.end(),
>      std::ptr_fun<const Point2&, const Point2&, bool>(comparePoints));
> then everything compiles fine.
> 
> Unfortunately both walkaround are unacceptable for different reasons.
> Any other possibilities?

I could think of two ways.
1) use an explicit cast. This is much like your second workaround, which
was unacceptable for a 'different' reason. So perhaps that reason
forbids this one too.

2) Use a wrapper function that is not overloaded.
Here is the modified code that does compile

<code>
#include <vector>
#include <algorithm>

struct Point2 {};
struct Point3 {};

bool comparePoints(const Point2& iP0, const Point2& iP1)
{return true;}
bool comparePoints(const Point3& iP0, const Point3& iP1)
{return true;}

typedef bool (*Point2PredPtr)(const Point2& , const Point2& );
// 1 typedef used in explicit cast

inline bool comparePoints2(const Point2& iP0, const Point2& iP1)
{return comparePoints(iP0, iP1);}
// wrapper function with a different (non overloaded) name

int main()
{
    std::vector< Point2 > array;
    std::sort(array.begin(), array.end(), (Point2PredPtr) comparePoints);
    std::sort(array.begin(), array.end(),  comparePoints2);
}
</code>


Geert-Jan Giezeman

-- 
      [ See http://www.gotw.ca/resources/clcm.htm
for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
 




 1 Posts in Topic:
Re: std::sort and overloaded compare function
Geert-Jan Giezeman <ge  2008-02-11 10:27:14 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Thu Sep 4 23:57:29 CDT 2008.