考虑这个工作代码。函数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*数据成员为11的value,这是具有“ 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;
                });
}


Demo

关于c++ - 指向数据成员的指针的可变列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33791376/

10-11 06:45