官术网_书友最值得收藏!

20. Container any, all, none

The requirement to be able to check the presence or absence of a variable number of arguments suggests that we should write variadic function templates. However, these functions require a helper function, a general-purpose one that checks whether an element is found in a container or not and returns a bool to indicate success or failure. Since all these functions, which we could call contains_all, contains_any, and contains_none, do is apply logical operators on the results returned by the helper function, we would use fold expressions to simplify the code. Short circuit evaluation is enabled after the expansion of the fold expression, which means we are evaluating only the elements that lead to a definitive result. So if we are looking for the presence of all 1, 2, and 3, and 2 is missing, the function will return after looking up value 2 in the container without checking value 3:

template<class C, class T>
bool contains(C const & c, T const & value)
{
return std::end(c) != std::find(std::begin(c), std::end(c), value);
}

template<class C, class... T>
bool contains_any(C const & c, T &&... value)
{
return (... || contains(c, value));
}

template<class C, class... T>
bool contains_all(C const & c, T &&... value)
{
return (... && contains(c, value));
}

template<class C, class... T>
bool contains_none(C const & c, T &&... value)
{
return !contains_any(c, std::forward<T>(value)...);
}
主站蜘蛛池模板: 久治县| 手游| 平乡县| 东辽县| 綦江县| 长春市| 武汉市| 手机| 盘山县| 济阳县| 商城县| 江孜县| 屏东县| 五台县| 夏邑县| 信丰县| 嘉祥县| 旬邑县| 博客| 中西区| 体育| 南木林县| 西畴县| 普格县| 海南省| 襄城县| 定边县| 广州市| 崇阳县| 嵊州市| 大兴区| 余庆县| 醴陵市| 宝应县| 精河县| 凌海市| 饶平县| 巩义市| 苏尼特右旗| 玉田县| 沁阳市|