- The Modern C++ Challenge
- Marius Bancila
- 219字
- 2021-06-25 22:01:27
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)...);
}
- 黑客攻防從入門(mén)到精通(實(shí)戰(zhàn)秘笈版)
- Java語(yǔ)言程序設(shè)計(jì)
- 解構(gòu)產(chǎn)品經(jīng)理:互聯(lián)網(wǎng)產(chǎn)品策劃入門(mén)寶典
- Mastering RabbitMQ
- 自制編譯器
- Python自動(dòng)化運(yùn)維快速入門(mén)(第2版)
- ASP.NET 3.5程序設(shè)計(jì)與項(xiàng)目實(shí)踐
- Create React App 2 Quick Start Guide
- Elasticsearch Essentials
- OpenMP核心技術(shù)指南
- Python自然語(yǔ)言理解:自然語(yǔ)言理解系統(tǒng)開(kāi)發(fā)與應(yīng)用實(shí)戰(zhàn)
- 遠(yuǎn)方:兩位持續(xù)創(chuàng)業(yè)者的點(diǎn)滴思考
- ABAQUS6.14中文版有限元分析與實(shí)例詳解
- 30天學(xué)通C#項(xiàng)目案例開(kāi)發(fā)
- JavaEE架構(gòu)與程序設(shè)計(jì)