specifically I have a list of objects of a class with multiple string object data members(NID, customerNumber, studentNumber, fName, lName).
I want to reuse the following code to search for the node that matches the search key whether the data member that is looked for is NID or any other of the class's string data members.
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
if it was PHP code I could use the value of a variable as the name of another:
$node->${$var}
but in C++ is there anyway to reuse the code?
The most flexible way to do this is to provide a predicate as a template parameter:
template <typename Pred>
Node * find_if(Node * node, Pred pred) {
for (; node && !pred(node); node = node->next);
return node;
}
In C++11, you can call it with a lambda:
if (Node * node = find_if(first, [&](Node * n){return n->NID == nid;})) {
// node points to the matching node
} else {
// not found
}
or, if you're stuck in ages past, a function object:
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));
or, since all your fields are strings, you could sacrifice flexibility for tersity using member pointers, giving something similar to your PHP example:
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);