Commit 33fc20ab authored by Tobias Hunger's avatar Tobias Hunger

Utils: Improve Utils::contains

* Consistently use anyOf to implement contains.
* Support contains over an container of std::unique_ptr matching a pointer.

Change-Id: I0180f3ec3d5935d8afeeac67a745d4b38a01674d
Reviewed-by: Eike Ziller's avatarEike Ziller <eike.ziller@qt.io>
parent 9b832f67
......@@ -96,11 +96,26 @@ void erase(T &container, F predicate)
template<typename T, typename F>
bool contains(const T &container, F function)
{
typename T::const_iterator begin = std::begin(container);
typename T::const_iterator end = std::end(container);
return anyOf(container, function);
}
typename T::const_iterator it = std::find_if(begin, end, function);
return it != end;
// Contains for normal pointers in std::vector<std::unique_ptr>
template<template<typename, typename...> class C, typename T, typename... Args>
bool contains(const C<T, Args...> &container, typename T::element_type *other)
{
return anyOf(container, [other](const typename C<T, Args...>::value_type &value) { return value.get() == other; });
}
template<typename T, typename R, typename S>
bool contains(const T &container, R (S::*function)() const)
{
return anyOf(container, function);
}
template<template<typename, typename...> class C, typename... Args, typename T, typename R, typename S>
bool contains(const C<T, Args...> &container, R (S::*function)() const)
{
return anyOf(container, function);
}
//////////////////
......
......@@ -60,6 +60,8 @@ struct Struct
bool isOdd() const { return member % 2 == 1; }
bool isEven() const { return !isOdd(); }
int getMember() const { return member; }
int member;
};
}
......@@ -205,6 +207,12 @@ void tst_Algorithm::contains()
std::vector<int> v1{1, 2, 3, 4};
QVERIFY(Utils::contains(v1, [](int i) { return i == 2; }));
QVERIFY(!Utils::contains(v1, [](int i) { return i == 5; }));
std::vector<Struct> structs = {2, 4, 6, 8};
QVERIFY(Utils::contains(structs, &Struct::isEven));
QVERIFY(!Utils::contains(structs, &Struct::isOdd));
QList<Struct> structQlist = {2, 4, 6, 8};
QVERIFY(Utils::contains(structQlist, &Struct::isEven));
QVERIFY(!Utils::contains(structQlist, &Struct::isOdd));
std::vector<std::unique_ptr<int>> v2;
v2.emplace_back(std::make_unique<int>(1));
v2.emplace_back(std::make_unique<int>(2));
......@@ -212,6 +220,10 @@ void tst_Algorithm::contains()
v2.emplace_back(std::make_unique<int>(4));
QVERIFY(Utils::contains(v2, [](const std::unique_ptr<int> &ip) { return *ip == 2; }));
QVERIFY(!Utils::contains(v2, [](const std::unique_ptr<int> &ip) { return *ip == 5; }));
// Find pointers in unique_ptrs:
QVERIFY(Utils::contains(v2, v2.back().get()));
int foo = 42;
QVERIFY(!Utils::contains(v2, &foo));
}
void tst_Algorithm::findOr()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment