tow*_*owi 10 c++ boolean explicit c++11
我正在玩新explicit的铸造操作员.如果你写的东西像
struct Data {
explicit operator string();
};
Run Code Online (Sandbox Code Playgroud)
不可能意外转换Data为string.所述darget数据类型bool是一个例外:在某些情况下,隐式转换是允许即使它被标记explicit- 上下文转换.因此,您可以在if(...)以下示例中使用此数据类型:
struct Ok {
explicit operator bool(); // allowed in if(...) anyway
};
Run Code Online (Sandbox Code Playgroud)
该段"25.4.(2)分类及相关业务"似乎让本作Compare的仿标箱状set为好.但是我对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};
}
Run Code Online (Sandbox Code Playgroud)
没有explicit前面operator bool()的例子编译.而我对"25.4.(2)"的理解是,这也应该用 `explicit来编译.
我是否正确理解了Std,因为转换set也explicit bool应该有效?那么这可能是gcc中的一个bug,还是我理解错了?
我对标准的理解有点不同——第 25.4 节涉及排序算法而不是排序容器;25.4.(1)中建立的上下文意味着25.4.(2)中指定的比较对象的属性适用于25.4中的算法,而不是排序容器
1 25.4 中的所有操作都有两个版本:一种采用 Compare 类型的函数对象,另一种使用运算符。
2 Compare 是函数对象类型 (20.8)。应用于 Compare 类型的对象的函数调用操作的返回值,当根据上下文转换为 bool (4) 时,如果调用的第一个参数小于第二个参数,则返回 true,否则返回 false。Compare comp 始终用于假设排序关系的算法。假设 comp 不会通过取消引用的迭代器应用任何非常量函数。
我不知道你的例子是否应该工作,但我不认为第 25.4 节适用于这里。
使用向量和 std::sort 进行快速测试有效:
#include <list>
#include <algorithm>
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::vector<int> data {2,3,4,1,2};
std::sort(std::begin(data), std::end(data), LessYesNo());
}
Run Code Online (Sandbox Code Playgroud)
编辑:
关联容器的 Compare 参数根据第 25.4 节定义:
1 关联容器提供基于键的数据快速检索。该库提供了四种基本类型的关联容器:set、multiset、map 和 multimap。
2 每个关联容器在 Key 和排序关系 Compare 上进行参数化,该排序关系在 Key 的元素上产生严格的弱排序(25.4)。另外,map和multimap将任意类型T与Key相关联。Compare类型的对象称为容器的比较对象。
23. 据我所知,Compare 类型没有其他条件,因此假设满足 25.4 约束的类型同样适用似乎确实合理。
| 归档时间: |
|
| 查看次数: |
2186 次 |
| 最近记录: |