Algorithm: Add a member variant for transform

Change-Id: I329ee764cc13dd8b794c6769a2baf2f41d6a9983
Reviewed-by: Eike Ziller <eike.ziller@qt.io>
This commit is contained in:
Orgad Shaneh
2017-03-09 22:11:11 +02:00
committed by Orgad Shaneh
parent bc562bbea9
commit 4136e36c6f
2 changed files with 24 additions and 10 deletions

View File

@@ -282,6 +282,15 @@ decltype(auto) transform(const C &container, R (S::*p)() const)
>::call(container, p); >::call(container, p);
} }
template<typename C,
typename R,
typename S>
Q_REQUIRED_RESULT
decltype(auto) transform(const C &container, R S::*member)
{
return transform(container, std::mem_fn(member));
}
// different container types for input and output, e.g. transforming a QList into a QSet // different container types for input and output, e.g. transforming a QList into a QSet
template<template<typename> class C, // result container type template<template<typename> class C, // result container type
typename SC, // input container type typename SC, // input container type

View File

@@ -42,6 +42,16 @@ int stringToInt(const QString &s)
return s.toInt(); return s.toInt();
} }
namespace {
struct Struct
{
Struct(int m) : member(m) {}
bool operator==(const Struct &other) const { return member == other.member; }
int member;
};
}
void tst_Algorithm::transform() void tst_Algorithm::transform()
{ {
// same container type // same container type
@@ -110,16 +120,11 @@ void tst_Algorithm::transform()
Utils::sort(i3); Utils::sort(i3);
QCOMPARE(i3, QList<int>({1, 1, 3})); QCOMPARE(i3, QList<int>({1, 1, 3}));
} }
} {
const QList<Struct> list({4, 3, 2, 1, 2});
namespace { const QList<int> trans = Utils::transform(list, &Struct::member);
struct Struct QCOMPARE(trans, QList<int>({4, 3, 2, 1, 2}));
{ }
Struct(int m) : member(m) {}
bool operator==(const Struct &other) const { return member == other.member; }
int member;
};
} }
void tst_Algorithm::sort() void tst_Algorithm::sort()