c++ - defining const and non-const version of traversal function -


i have datastructure similar list:

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

and 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 need const , non-const version of traverse function accepts either const node<t>& list or node<t>& list, depending on context, preferably avoiding code duplication. how achieved?

a possible solution creating static template function takes *this forwarding reference:

class node { private:     template <typename tself>     static void traverse_impl(tself& self, node<t>& list, unaryop op)     {         node<t>* current = &list;         while(current)         {             op(*current);             current = current->next.get();         }     }  public:     void traverse(node<t>& list, unaryop op)     {         traverse_impl(*this, list, op);     }      void traverse(node<t>& list, unaryop op) const     {         traverse_impl(*this, list, op);     } }; 

this works because of template argument deduction rules - in short, tself accept both const , non-const references.

if need access members of this inside traverse_impl, use self.member.

additionally, can use std::conditional or similar facilities inside traverse_impl different things depending on const-ness of tself. can use forwarding reference (tself&&) , handle case this being moved ref-qualifiers , perfect-forwarding.


Comments