考虑这个工作代码。函数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
中搜索Object*
,其Thing*
数据成员的value
数据成员为11,即Object*
1}}有“汤姆”。对数据成员的指针链有多大可以传递到searchByDataMember
是没有限制的。
答案 0 :(得分:1)
您需要一种方法来连续应用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;
});
}