Re: Error when using std::less
On Jun 10, 8:32 pm, desktop <f...@sss.com> wrote:
I get this error when I run my program:
red_black_tree.cpp:188: error: no matching function for call to
?std::less<MyObj<int> >::less(MyObj<int>&, MyObj<int>&)?
/usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/stl_=
function.h:224:
note: candidates are: std::less<MyObj<int> >::less()
/usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/stl_=
function.h:224:
note: std::less<MyObj<int> >::less(const
std::less<MyObj<int> >&)
The code is rather comprehensive so I have just included the code that
causes the error below (where C is std::less as default):
/* used for testing. */
template <typename K, typename V, typename F, typename C, typename A,
typename N, bool B>
typename red_black_tree<K, V, F, C, A, N, B>::iterator
red_black_tree<K, V, F, C, A, N, B>::test_tree(value_type e1, value_type
e2) {
// this does not work!
if (C(e1,e2)) {
C is a type, so C(e1,e2) is (formally) a function style type
conversion, or (more usually) an explicit call of the
constructor. You create a new, temporary instance of whatever C
is, which is then converted to bool. Except, of course, that if
C doesn't have an appropriate constructor, or doesn't have an
implicit conversion to bool, you'll get a compiler error.
If std::less is an acceptable argument for C, you want:
if ( C()( e1, e2 ) ) {
More likely, however, you'd want a member of the class with type
C, and use it. This will also allow passing specific instances
of the class to the constructor, and using them to instantiate
the class member, something that is necessary if, like the
standard classes, you want to support pointers to functions as
well.
It seems that less can only be used like:
less()
or
less(const std::less<MyObj<int> >&)
Those are the only two constructors for std::less.
But that is not how I use it or have read that it is supposed
to be used.
I think you're confusing type and object. std::less is a type.
The name of a type can be used to create or declare objects of
that type, but that's about it. What you want is an object of
type std::less, on which you can call member functions,
and---because std::less has an overridden operator()()---you can
use as if it were a function.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34