具体来说,我有一个包含多个字符串对象数据成员(NID、customerNumber、studentNumber、fName、lName)的类的对象列表。
我想重用以下代码来搜索与搜索键匹配的节点,无论要查找的数据成员是 NID 还是该类的任何其他字符串数据成员。
nodePtr = firstPtr;
for(; nodePtr != NULL && nodePtr->str != str; nodePtr = nodePtr->nextPtr);
if(nodePtr != NULL)
//the nodePtr points to the node that matches the search key
else
//no node matched the search key
如果是 PHP 代码,我可以使用一个变量的值作为另一个变量的名称:
$node->${$var}
但是在 C++ 中是否有重用代码的方法?
最佳答案
最灵活的方法是提供一个谓词作为模板参数:
template <typename Pred>
Node * find_if(Node * node, Pred pred) {
for (; node && !pred(node); node = node->next);
return node;
}
在 C++11 中,您可以使用 lambda 调用它:
if (Node * node = find_if(first, [&](Node * n){return n->NID == nid;})) {
// node points to the matching node
} else {
// not found
}
或者,如果你停留在过去的时代,一个函数对象:
struct CompareNID {
CompareNID(std::string nid) : nid(nid) {}
bool operator() {Node * n) {return n->NID == nid;}
std::string nid;
};
Node * node = find_if(first, CompareNID(nid));
或者,由于您所有的字段都是字符串,您可以使用成员指针牺牲灵 active 以换取简洁性,给出类似于您的 PHP 示例的内容:
Node * find(Node * node, std::string Node::*member, std::string const & value) {
for (; node && node->*member != value; node = node->next);
return node;
}
Node * node = find(first, &Node::NID, nid);
关于c++ - 重复使用相同的代码对列表中对象的不同数据成员执行相同的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14581704/