473,390 Members | 1,285 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,390 software developers and data experts.

trouble when overloading function used as predicate in std::sort

I accidently overloaded a static member function that I use as predicate
in the std::sort() for a vector and ended up with a compiler error. Is
this kind of overload not allowed for predicates and if so, why not?
Shouldn the compiler be able to tell which of he overloaded functions to
use?

The second A::comp() is the one I accidently added and gives the error
message (in Borland C++Builder 6)

[C++ Error] Unit1.cpp E2285 Could not find a match for
'sort<_RandomAccesIter, _Compare>(A*,A*,bool(*)(const A&,const A&))'

Commenting out the line makes the code compile just fine.

//---------------------------------------------------------------------------
#include <vector>
#include <algorithm>

using namespace std;

struct A {
int a;
A(int a0): a(a0) {}
static bool comp ( const A a1, const A & a2) {return a1.a<a2.a;}
static bool comp ( const A a1 ){ return true; } //< causes
compiler error
};

int main(int argc, char* argv[])
{
vector<A> a;
a.push_back(A(4));
a.push_back(A(7));
sort( a.begin(), a.end(), A::comp );

return 0;
}
//---------------------------------------------------------------------------

--
<- remove capital x:s from e-mail to reply ->

Jul 22 '05 #1
4 3299

"hall" <Xc***********@yahoo.se> wrote:
I accidently overloaded a static member function that I use as predicate
in the std::sort() for a vector and ended up with a compiler error. Is
this kind of overload not allowed for predicates and if so, why not?
Shouldn the compiler be able to tell which of he overloaded functions to
use?

The second A::comp() is the one I accidently added and gives the error
message (in Borland C++Builder 6)

[C++ Error] Unit1.cpp E2285 Could not find a match for
'sort<_RandomAccesIter, _Compare>(A*,A*,bool(*)(const A&,const A&))'

Commenting out the line makes the code compile just fine.

//---------------------------------------------------------------------------
#include <vector>
#include <algorithm>

using namespace std;

struct A {
int a;
A(int a0): a(a0) {}
static bool comp ( const A a1, const A & a2) {return a1.a<a2.a;}
static bool comp ( const A a1 ){ return true; } //< causes
compiler error
};

int main(int argc, char* argv[])
{
vector<A> a;
a.push_back(A(4));
a.push_back(A(7));
sort( a.begin(), a.end(), A::comp );

return 0;
}


Well, one thing that bothers me is that sort() expects the
predicate to have argument signature:

(const A&, const A&)

but you use:

(const A , const A&)

Forget the '&'?

That may not be related to your problem, but it's
an error you should look into.

I did try compiling your program on DJGPP (a port of the
Gnu C++ compiler to Windows-command-prompt environment,
from www.delorie.com ). I got this:

wd=C:\C\test
%make predicate-test
gpp -IC:/C/lib -pedantic -Wall -W -Wshadow -Wcast-qual -Wcast-align -Wconversion
-Os -s -LC:/C/lib predicate-test.cpp -lrh -lm -o C:/Software/predicate-test.exe

predicate-test.cpp: In function `int main()':
predicate-test.cpp:19: error: no matching function for call to `sort(
__gnu_cxx::__normal_iterator<A*, std::vector<A, std::allocator<A> > >,
__gnu_cxx::__normal_iterator<A*, std::vector<A, std::allocator<A> > >,
<unknown type>)'
make.exe: *** [predicate-test] Error 1

But when I comment-out the extra version of comp, it compiles fine.

I get the same results if I take the comp's out of the class and
make them global functions. I even changed the extra comp to
a totally unrelated signature:

double comp (int a, char b)
{
return a + b;
}

But any way I try it, the extra comp apparently causes
the compiler to see "comp" in your call to sort() as being
an "unknown type".

Perhaps the problem is related to the fact that the name "comp"
is a pointer to a function. Perhaps sort() can't check signatures
and relies on an unambiguous pointer-to-function called "comp",
which would preclude overloading.
--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant


----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Jul 22 '05 #2


Robbie Hatley wrote:
"hall" <Xc***********@yahoo.se> wrote:

I accidently overloaded a static member function that I use as predicate
in the std::sort() for a vector and ended up with a compiler error. Is
this kind of overload not allowed for predicates and if so, why not?
Shouldn the compiler be able to tell which of he overloaded functions to
use?

The second A::comp() is the one I accidently added and gives the error
message (in Borland C++Builder 6)

[C++ Error] Unit1.cpp E2285 Could not find a match for
'sort<_RandomAccesIter, _Compare>(A*,A*,bool(*)(const A&,const A&))'

Commenting out the line makes the code compile just fine.

//---------------------------------------------------------------------------
#include <vector>
#include <algorithm>

using namespace std;

struct A {
int a;
A(int a0): a(a0) {}
static bool comp ( const A a1, const A & a2) {return a1.a<a2.a;}
static bool comp ( const A a1 ){ return true; } //< causes
compiler error
};

int main(int argc, char* argv[])
{
vector<A> a;
a.push_back(A(4));
a.push_back(A(7));
sort( a.begin(), a.end(), A::comp );

return 0;
}

Well, one thing that bothers me is that sort() expects the
predicate to have argument signature:

(const A&, const A&)

but you use:

(const A , const A&)

Forget the '&'?


Ah, yes, the & apperantly got lost when I wrote the example. However it
was (const A& , const A&) in the piece of code where the problem first
occured.

That may not be related to your problem, but it's
an error you should look into.

I did try compiling your program on DJGPP (a port of the
Gnu C++ compiler to Windows-command-prompt environment,
from www.delorie.com ). I got this:

wd=C:\C\test
%make predicate-test
gpp -IC:/C/lib -pedantic -Wall -W -Wshadow -Wcast-qual -Wcast-align -Wconversion
-Os -s -LC:/C/lib predicate-test.cpp -lrh -lm -o C:/Software/predicate-test.exe

predicate-test.cpp: In function `int main()':
predicate-test.cpp:19: error: no matching function for call to `sort(
__gnu_cxx::__normal_iterator<A*, std::vector<A, std::allocator<A> > >,
__gnu_cxx::__normal_iterator<A*, std::vector<A, std::allocator<A> > >,
<unknown type>)'
make.exe: *** [predicate-test] Error 1

But when I comment-out the extra version of comp, it compiles fine.

I get the same results if I take the comp's out of the class and
make them global functions. I even changed the extra comp to
a totally unrelated signature:

double comp (int a, char b)
{
return a + b;
}

But any way I try it, the extra comp apparently causes
the compiler to see "comp" in your call to sort() as being
an "unknown type".

Perhaps the problem is related to the fact that the name "comp"
is a pointer to a function. Perhaps sort() can't check signatures
and relies on an unambiguous pointer-to-function called "comp",
which would preclude overloading.


Yes, so it seems. I am interested to find out more precisly why the
compiler cannot tell which version of comp to use. As the compiler error
messages in this case didn't help much (at least not me), it would be
good to know if this problem may occur somwhere else.

I made a small test for the pointer theory:

//------------------------------------------------------------------------
#include <string>
#include <iostream>
using namespace std;

void fun (int &i){ cout << "fun(int&): "<<i; }
void fun (string s) {cout << "fun(string&): "<<s;}
foo( void (*f)(int&)){ f(1); }

int main(int argc, char* argv[])
{
foo(fun);
return 0;
}
//---------------------------------------------------------------------------
This will compile and correctly run fun(int&), so here the compiler
seems to know which of the overloaded fun() to use. Now, pointers to
functions aren't someting i'm good at, so this may not be an equivalent
case to the original problem with std::sort(). But then what is the
difference? The fact that sort is templatized?

Any comments are appreachiated.

regards
hall

--
<- remove capital x:s from e-mail to reply ->

Jul 22 '05 #3
>
Yes, so it seems. I am interested to find out more precisly why the
compiler cannot tell which version of comp to use. As the compiler error
messages in this case didn't help much (at least not me), it would be
good to know if this problem may occur somwhere else.


You are confusing two different processes. The first process is template
argument deduction. std::sort has a definition something like this

template <class I, class F>
void sort(I first, I last, F comp)
{
...
}

and when you call std::sort the compiler attempt to match the types you
supply with the types in the template. Now here's the rub, sort is defined
with a third parameter F, *anything* will match this parameter, literally
anything, int, string, bool, you name it. Obviously in this situation the
compiler cannot decide between your two versions of comp because they both
match. It is only later that the compiler says, well now I know what F is,
does it make sense with the actual code of std::sort.

It would be a different story if sort was defined like this

template <class I, class T>
void sort(I first, I last, bool (*comp)(T, T))
{
...
}

because then obviously only the two argument version of your comp function
could match. However std::sort isn't defined like that probably because it
would mean std::sort could only be used with function pointers and not
functors.

john
Jul 22 '05 #4


John Harrison wrote:

[snip]

It would be a different story if sort was defined like this

template <class I, class T>
void sort(I first, I last, bool (*comp)(T, T))
{
...
}

This is how i thought that sort was defined and thus my confusion, but
as you explain below, this definition would not be a good idea.
because then obviously only the two argument version of your comp
function could match. However std::sort isn't defined like that
probably because it would mean std::sort could only be used with
function pointers and not functors.

john


Thanks!
hall
--
<- remove capital x:s from e-mail to reply ->

Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: matthias_k | last post by:
Hi, I need to sort elements of a std::list using a function predicate, something like: bool predicate( const& M m1, const& M m2 ) { return m1.somedata < m2.somedata; } I tried to call...
3
by: 77123036 | last post by:
why this programme cannot be built in vc6(there are two link error),but successful in gcc? ------------------ #include <iostream> #include <algorithm> template <class T> inline bool less(T...
8
by: Manfred | last post by:
Hello I am new to template programming, so i tried the 'example' from http://www.sgi.com/tech/stl/functors.html. I can compile the code but when i want to run the program I get a segmentation...
0
by: Eugene | last post by:
Hi everybody! Got the logical error (wrong row (SSN) selected on SelectedIndexChange event) when made a sort by non-key field in Datagrid. Used this Sub to keep the keyfield ("SSN"): ...
5
by: Peter Olcott | last post by:
I created an object that requires access to another objects data, yet have found no good way to pass this data as a parameter because the member function that requires this data must be a binary...
4
by: prakashsahni | last post by:
I am using a sort func object like struct mystruct { bool operator () (MyClass* const &a, MyClass* const&b) {}; } Invoke it like std::sort(vec.begin(), vec.end(),mystruct); Where vec is an...
11
by: Jeff Schwab | last post by:
Would std::sort ever compare an object with itself? I'm not talking about two distinct, equal-valued objects, but rather this == &that. The container being sorted is a std::vector. I've never...
1
by: Markus Dehmann | last post by:
In the following code example, I define several Comparator classes which contain different compare functions to use with std::sort. I have a Sorter class that gets passed a Comparator and is...
10
by: ikarus | last post by:
Hello C++ Gurus! I'm comparing sorting algorithm for study goals. I've compared STL std::sort and hand-coded introsort on millions (tens of millions) of integers array sorting. It was tested...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.