【发布时间】:2011-11-04 17:44:00
【问题描述】:
我正在为演员操作员使用新的explicit。如果你写类似
struct Data {
explicit operator string();
};
不可能意外地将Data 转换为string。目标数据类型bool 是一个例外:在某些情况下,即使标记为explicit,也允许隐式转换——上下文转换。因此,您可以在 if(...) 中使用此数据类型,例如:
struct Ok {
explicit operator bool(); // allowed in if(...) anyway
};
“25.4.(2) 排序和相关操作” 段落似乎也允许像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)”的理解是,这也应该编译with`explicit.
我是否正确理解了 set 和 explicit bool 转换应该有效的标准? 那么这可能是 gcc 中的错误,还是我理解错误?
【问题讨论】:
-
我同意您对 FWIW 标准的阅读。你从 gcc 得到什么错误?
-
我同意它似乎是这样解释的,所以它可能还没有在 gcc 中实现(当编译器仍然正在编写时,我对谈论错误持谨慎态度)。
标签: c++ c++11 boolean explicit