我正在玩新explicit
的演员操作员。如果你写类似
struct Data {
explicit operator string();
};
不可能意外转换Data
为string
. darget 数据类型bool
是一个例外:在某些情况下,即使标记为explicit
- contextual conversion ,也允许隐式转换。因此,您可以在示例中使用此数据类型if(...)
:
struct Ok {
explicit operator bool(); // allowed in if(...) anyway
};
段落“25.4.(2) 排序和相关操作”似乎也允许标准容器Compare
的函子这样做。但是我对 gcc-4.7.0 的尝试失败了,我注意到这是我的误解还是 gcc 中的错误?set
#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};
}
在示例编译explicit
之前没有。operator bool()
而我对“25.4.(2)”的理解是,这也应该使用`explicit.
我是否正确理解了转换set
也explicit
bool
应该起作用的标准?那么这可能是gcc中的一个错误,还是我理解错误?