Imitation function __jquery of C + +

Source: Internet
Author: User

Http://www.cnblogs.com/runnyu/p/6010101.html

Imitation function: function object;

An imitation function (functors) is actually an object that overloads the operator ()

#include <iostream>
using namespace std;

Template<typename t>
struct m_plus
{
    T operator () (const t& x, const t& y) {return x + y;}
};

int main (int argc, char *argv[])
{
    //define its object  invoke its operator ()
    m_plus<int> op;
    cout << op (1, 2) << Endl;
    Generate an Anonymous object  This is the main use of the imitation function
    cout << m_plus<int> () (1, 2) << Endl;
    return 0;
}

1. Imitation functions can have their own state, and function pointers are not (some use template or static variables can be implemented).

We can do this by using an imitation function:

#include <iostream>
using namespace std;

Template<typename T, t add>
struct m_plus
{
    m_plus () {_add = add;}
    T operator () (const t& x) {return x + _add;}
    The affine function can have its own state
    int _add;

int main (int argc, char *argv[])
{
    m_plus<int, 10> op;
    cout << op (m) << Endl;
    cout << op << endl;
    return 0;
}

2. Imitation functions can be used in combination with function adapters.

For example, if we want to use the COUNT_IF algorithm to compute the number of elements in the container that are greater than 10.

If we use greater<int> as a discriminant (two yuan), and count_if only accept a unary discriminant, then we need to work with the function adapter.

and function pointers can not be used directly with the function adapter, specifically in the analysis of bind2nd will be mentioned.

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm >
using namespace std;


int main (int argc, char *argv[])
{
    vector<int> coll{1, 3, 5, 7, 9, One,};
    Then there are the specific implementations of bind2nd
    cout << count_if (Coll.begin (), Coll.end (), bind2nd (Greater<int> (), ten)) << Endl;
    return 0;
}



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.