Bjarne: What is a function object?

Source: Internet
Author: User

As the name implies, it is an object that represents a function in a certain way. Typically, it refers to an instance of a class, which defines the application Operator ().
Function objects are more common than functions, because function objects can define persistent parts that span multiple calls (similar to static local variables ), at the same time, it can be initialized and checked outside the object (different from static local variables ). For example:

Class sum {
Int val;
Public:
Sum (int I): Val (I ){}
Operator int () const {return val;} // get the value
Int operator () (int I) {return Val + = I;} // Application
};

Void F (vector V)
{
Sum S = 0; // Initial Value 0
S = for_each (V. Begin (), V. End (), S); // calculate the sum of all elements
Cout <"the sum is" <S <"/N ";

// Or even:
Cout <"the sum is" <for_each (V. Begin (), V. End (), sum (0) <"/N ";
}

Note that a function object with an application operator can be perfectly inline because it does not involve any pointers, and the latter may cause a rejection of optimization. In contrast, the existing optimizer is almost impossible (or completely unavailable ?) Concatenates a call using a function pointer.

In the standard library, function objects are widely used for elasticity.

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.