考虑一下这个工作代码。函数searchByDataMember
使用指向数据成员的指针作为参数来在容器中搜索值。
#include <iostream>
#include <list>
#include <string>
template <typename Container, typename T, typename DataPtr>
typename Container::value_type searchByDataMember (const Container& container, const T& t,
DataPtr ptr) {
for (const typename Container::value_type& x : container) {
if (x->*ptr == t)
return x;
}
return typename Container::value_type{};
}
struct Object {
int ID, value;
std::string name;
Object (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
};
std::list<Object*> objects { new Object(5,6,"Sam"), new Object(11,7,"Mark"),
new Object(9,12,"Rob"), new Object(2,11,"Tom"), new Object(15,16,"John") };
int main() {
const Object* object = searchByDataMember (objects, 11, &Object::value);
std::cout << object->name << 'n'; // Tom
}
那么,在指向自己的数据成员有数据成员要搜索的情况下,如何将以上内容扩展到使用指向数据成员的指针的可变列表作为参数呢?例如,
#include <iostream>
#include <list>
#include <string>
template <typename Container, typename T, typename... DataPtrs>
typename Container::value_type searchByDataMember (const Container& container, const T& t,
DataPtrs... ptrs) {
// What to put here???
}
struct Thing {
int ID, value;
std::string name;
Thing (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
};
struct Object {
int rank;
Thing* thing;
Object (int r, Thing* t) : rank(r), thing(t) {}
};
std::list<Object*> objects { new Object(8, new Thing(5,6,"Sam")), new Object(2, new Thing(11,7,"Mark")),
new Object(1, new Thing(9,12,"Rob")), new Object(9, new Thing(2,11,"Tom"))};
int main() {
// The desired syntax.
// const Object* object = searchByDataMember (objects, 11, &Object::thing, &Thing::value);
// std::cout << object->thing->name << 'n'; // Tom (the desired output)
}
因此,在这里,我们希望在容器objects
中搜索具有Thing*
数据成员的Object*
,其value
数据成员为11,即具有"Tom"的Object*
。指向数据成员的指针链可以传递到searchByDataMember
的大小没有限制。
您需要一种连续应用operator ->*
的方法:
template <typename T, typename MPtr>
auto arrow(T* obj, MPtr mptr)
{
return obj->*mptr;
}
template <typename T, typename MPtr, typename ... MPtrs>
auto arrow(T* obj, MPtr mptr, MPtrs... mptrs)
{
return arrow(obj->*mptr, mptrs...);
}
然后你的搜索函数很简单,比如:(我更喜欢返回迭代器而不是值btw)
template <typename Container, typename T, typename... DataPtrs>
auto searchByDataMember (const Container& container, const T& t, DataPtrs... ptrs)
{
return std::find_if(std::begin(container), std::end(container),
[&](const auto&e) {
return arrow(e, ptrs...) == t;
});
}
演示