I am playing around with the new explicit for cast-operators. If you write something like
struct Data {
explicit operator string();
};
It is not possible to accidentally convert Data to string. The darget data type bool is an exception: In certain cases the implicit conversion is allowed even if it is marked explicit — contextual conversion. So, you can use this data types in an if(...) for example:
struct Ok {
explicit operator bool(); // allowed in if(...) anyway
};
The paragraph “25.4.(2) Sorting and related operations” seems to allow this for the Compare functor of standard containers like set as well. But my tries with gcc-4.7.0 fail, and I am note sure if it is my mis-understanding or a bug in gcc?
#include <set>
struct YesNo { // Return value type of Comperator
int val_;
explicit YesNo(int y) : val_{y} {}
/* explicit */ operator bool() { return val_!=0; }
};
static const YesNo yes{1};
static const YesNo no{0};
struct LessYesNo { // Comperator with special return values
YesNo operator()(int a, int b) const {
return a<b ? yes : no;
}
};
int main() {
std::set<int,LessYesNo> data {2,3,4,1,2};
}
Without the explicit before operator bool() the example compiles. And my understanding of “25.4.(2)” is, that this should also compile with the `explicit.
Did I understand the Std correctly that for set also explicit bool conversions should work? And might this be a bug in gcc then, or did I understand something wrong?
My reading of the standard is a little different –
section 25.4 deals with sorting algorithms rather than for sorted containers; the context established in 25.4.(1) means that the property of the compare object specified in 25.4.(2) applies to the algorithms in 25.4, not to sorted containers
I don’t know whether your example should work or not, but I don’t think section 25.4 is applicable here.
A quick test with a vector and std::sort works:
Edit:
The associative container’s Compare parameter is defined in terms of secion 25.4:
and 23. has no other conditions on the type of Compare as far as I can see, so it does seem reasonable to assume that a type satisfying the constraints of 25.4 are equally applicable.