C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 将明确的bool类型隐式转换为排序容器?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_0@
我正在为演员运用新的显式.如果你写的东西
struct Data {
    explicit operator String(); 
};

不可能将数据意外转换为字符串. darget数据类型bool是一个例外:在某些情况下,即使将其标记为显式 – 上下文转换,也允许隐式转换.因此,您可以在if(…)中使用此类型的数据,例如:

struct Ok {
    explicit operator bool(); // allowed in if(...) anyway
};

段落“25.4.(2)排序和相关操作”似乎允许这样的标准容器的比较函数,如设置.但是我的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};
}

没有明确的操作符bool()之前的示例编译.而我对“25.4.(2)”的理解是,也应该用“明确的”来编译.

我明白了Std是否正确的设置也是明确的bool转换应该工作?这可能是gcc中的错误,还是我明白错了?

解决方法

我的阅读标准有点不同 –
第25.4节处理排序算法,而不是排序容器; 25.4.(1)中建立的上下文意味着25.4.(2)中规定的比较对象的属性适用于25.4中的算法,不适用于排序容器

我不知道你的例子是否应该工作,但我不认为这里适用第25.4节.

使用vector和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,2};
    std::sort(std::begin(data),std::end(data),LessYesno());
}

编辑:

关联容器的Compare参数按照第25.4节定义:

和23.对于比较类型没有其他条件,据我所见,所以假设满足25.4约束的类型同样适用,似乎是合理的.

大佬总结

以上是大佬教程为你收集整理的c – 将明确的bool类型隐式转换为排序容器?全部内容,希望文章能够帮你解决c – 将明确的bool类型隐式转换为排序容器?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。