c – 将明确的bool类型隐式转换为排序容器?

前端之家收集整理的这篇文章主要介绍了c – 将明确的bool类型隐式转换为排序容器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为演员运用新的显式.如果你写的东西
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中的算法,不适用于排序容器

1
All the operations in 25.4 have two versions: one that takes a
function object of type Compare and one that uses an operator.

2
Compare is a function object type (20.8). The return value of the
function call operation applied to an object of type Compare,when
contextually converted to bool (4),yields true if the first argument
of the call is less than the second,and false otherwise. Compare comp
is used throughout for algorithms assuming an ordering relation. It is
assumed that comp will not apply any non-constant function through the
dereferenced iterator.

我不知道你的例子是否应该工作,但我不认为这里适用第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节定义:

1 Associative containers provide fast retrieval of data based on keys. The library provides four basic kinds of associative containers: set,multiset,map and multimap.

2 Each associative container is parameterized on Key and an ordering relation Compare that
induces a strict weak ordering (25.4) on elements of Key. In addition,map and multimap associate an arbitrary type T with the Key. The object of type Compare is called the comparison object of a container.

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

原文链接:https://www.f2er.com/c/116053.html

猜你在找的C&C++相关文章