What is boost: visit_each?

I read the documentation onvisit_each , but I can’t understand what exactly he is doing, as well as the general use for it, if every user needs to overload it anyway. Does anyone want to enlighten me?


Change . Perhaps I am so confused because the following content <boost/visit_each.hpp>, and I just do not see the “magic” there to “visit every subobject”:

namespace boost {
  template<typename Visitor, typename T>
  inline void visit_each(Visitor& visitor, const T& t, long)
  {
    visitor(t);
  }

  template<typename Visitor, typename T>
  inline void visit_each(Visitor& visitor, const T& t)
  {
    visit_each(visitor, t, 0);
  }
}

Can someone please give me a concrete example of how this should look / work?

+5
source share
2 answers

, : ", , T , ". , , , . , , - , , , .

, ... , , , , visit_each , 't .

signals::trackable. , , . is_trackable. - .

struct trackable { };

struct Introspective {
    int a;
    double b;
    trackable c;
};

struct NotIntrospective {
    int a;
    double b;
    trackable c;
};

template<typename Visitor, typename T>
inline void visit_each(Visitor& visitor, const T& t, long) {
  visitor(t);    
} 

template<typename Visitor>
inline void visit_each(Visitor& visitor, const Introspective& t, int) {
  visitor(t); //"visits" the object as a whole

  //recursively visit the member objects; if unspecialized, will simply call `visitor(x)`
  visit_each(visitor, t.a, 0);
  visit_each(visitor, t.b, 0);
  visit_each(visitor, t.c, 0);
}

struct is_trackable {
  void operator()(const trackable&) { 
    //Do something
  }

  template<typename T>
  void operator()(const T&) { }
}

int main() {
    Introspective a;
    NotIntrospective b;
    trackable c;

    visit_each(is_trackable(), a, 0); //calls specialized version, finds `a.c`
    visit_each(is_trackable(), b, 0); //calls default version, finds nothing
    visit_each(is_trackable(), c, 0); //calls default version, which "visits" the 
                                      //object itself, and finds that it is trackable
}

, visit_each , visit_each, .

+1
+2

All Articles