Study on function object 9 visit_each

Source: Internet
Author: User

The boost: visit_each template is defined in the visit_each.hpp file.

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);  }}

This provides a simple mechanism. The constt & T parameter is the observed object, and the visitor & visitor parameter is the function object used to observe T. Therefore, the operator () function must be implemented, then it will be called within visist_each:

Visitor (t)

The third parameter long will be abolished in the future. Currently, only 0 can be passed.

The following is a simple example:

struct A {    A():y(3), z(5) {            }        int y;        int z;};template<class T>struct Visitor {    void operator()(T const& t) {        cout << t.y << endl;        cout << t.z << endl;    }};
int main(int argc, char** argv) {    A b;    Visitor<A> v;    visit_each(v, b, 0);    return 0;}

Running result:

35

There is a problem right away. Why does visit_each need this? This should be the implementation of the C ++ template of the visitor design mode. Do not design the visitor interface and specific subclass. You only need to design your own class and access the visitor function object of this class.

Classic Visitor Design Patterns can refer to a blog: http://blog.csdn.net/superbeck/article/details/5325991

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.