vendredi 2 septembre 2016

defining const and non-const version of traversal function

I have a datastructure similar to a list:

template<typename T>
struct node {
  T val;
  unique_ptr<node<T>> next;
};

and a simple traversal function:

template<typename T, typename UnaryOp>
void traverse(node<T>& list, UnaryOp op) {
  node<T>* current = &list;
  while(current) {
    op(*current);
    current = current->next.get();
}

I now need a const and a non-const version of the traverse function, preferably avoiding code duplication. How could this be achieved?

Aucun commentaire:

Enregistrer un commentaire