1

考虑这个工作代码。该函数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)
}

所以这里我们希望在容器中搜索 具有数据成员为 11的数据成员的容器objects,即具有“Tom”的容器。指向数据成员的指针链可以传递到.Object*Thing*valueObject*searchByDataMember

4

1 回答 1

2

你需要一种方式来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;
                });
}

演示

于 2015-11-18T22:37:28.587 回答