Topic: Library conformance question
Author: vaps4bm@prism.gatech.edu (Brian McNamara!)
Date: 2000/10/03 Raw View
Is this program legal?
#include <algorithm>
struct Useless {};
struct Evil {
operator bool() const { return true; }
Useless operator!() const { return Useless(); }
};
struct Comp {
Evil operator()( int, int ) { return Evil(); }
};
int main() {
int a[10];
std::binary_search( a, a+10, 5, Comp() );
}
I think it is; I think std::binary_search only requires that its
comparator argument have a result type that is "convertible to bool" and
thus "Evil" counts.
Nevertheless, I have seen implementations that work along the lines of
template <class FI, class T, class Comp>
bool binary_search(FI first, FI last, const T& val, Comp comp) {
FI i = lower_bound(first, last, val, comp);
return i != last && !comp(val, *i);
}
and such a library implementation makes my program fail to compile. My
impression is that the standard would require a conforming
implementation to do something like
template <class FI, class T, class Comp>
bool my_binary_search(FI first, FI last, const T& val, Comp comp) {
FI i = lower_bound(first, last, val, comp);
bool b = comp(val, *i);
return i != last && !b;
}
This makes me glad I am not a library implementer.
Comments?
--
Brian McNamara
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]
Author: James Kuyper <kuyper@wizard.net>
Date: 2000/10/04 Raw View
"Brian McNamara!" wrote:
>
> Is this program legal?
>
> #include <algorithm>
>
> struct Useless {};
>
> struct Evil {
> operator bool() const { return true; }
> Useless operator!() const { return Useless(); }
> };
>
> struct Comp {
> Evil operator()( int, int ) { return Evil(); }
> };
>
> int main() {
> int a[10];
> std::binary_search( a, a+10, 5, Comp() );
> }
>
> I think it is; I think std::binary_search only requires that its
> comparator argument have a result type that is "convertible to bool" and
> thus "Evil" counts.
The standard specifies in 25.3p2 that the function object must return
either true or false. Not a value of a type convertible to those values;
it must actually return one of those values.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.research.att.com/~austern/csc/faq.html ]
[ Note that the FAQ URL has changed! Please update your bookmarks. ]