我正在尝试使用新的explicit
转换运算符。如果你像这样写:
struct Data {
explicit operator string();
};
无法意外地将Data
转换为string
。 目标数据类型bool
是一个例外:在某些情况下,即使标记为explicit
,也允许隐式转换——上下文转换。 因此,您可以在例如if(...)
中使用这些数据类型:
struct Ok {
explicit operator bool(); // allowed in if(...) anyway
};
这段话中的"25.4.(2) Sorting and related operations"似乎也允许像set
这样的标准容器使用Compare
函数对象。但我尝试使用gcc-4.7.0时失败了,我不确定是我的误解还是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};
}
在operator bool()
之前没有加上explicit
,示例也可以编译。根据我对“25.4.(2)”的理解,这应该也可以使用explicit
。我的理解是,对于set
,显式的bool
转换也应该起作用吗?这可能是gcc中的一个错误,还是我理解错了什么?