Function adapter for member functions

Source: Internet
Author: User

In addition to providing regular function adapters, the STL standard library also provides two function adapters for member functions. Their main function is to use these adapters, you can directly call its member functions for each element.

There are two such member function adapters:

Mem_fun_ref (OP) calls the object's member function op

Mem_fun (OP) calls the object pointer member function op

Both function receivers call the member function op in the object. For these two member functions, the const member function of the object can only be called in the past, but the current situation seems to have changed, all member functions can be called.

An example is as follows:

# Include <iostream> # include <functional> # include <deque> # include <algorithm> # include <iterator> using namespace STD; Class A {public: A (int B ): A (B ){}~ A () {} void mfun () {ostream_iterator <int> (cout, "--") = ++ A;} PRIVATE: int A ;}; int main () {deque <A> de; For (INT I = 0; I <5; I ++) de. push_back (A (I); for_each (de. begin (), de. end (), mem_fun_ref (& A: mfun); cout <Endl; deque <A *> de2; For (INT I = 0; I <5; I ++) de2.push _ back (new A (I); for_each (de2.begin (), de2.end (), mem_fun (& A: mfun )); /* 1--2--3--4--5--1--2--3--4--5 -- press any key to continue... */}

Note:

1. The member functions called through this type of adapter must exist in the object type.

2. The parameters of the two receivers must be the offset of the member functions in the type passed, and the function name cannot be directly transferred.

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.