C ++ function object

Source: Internet
Author: User

Function object

Classes that define call operators. Their objects are often called function objects, that is, they are objects that act similar functions.

Struct absint

{

Int operator () (INT Val)

{

Return Val <0? -Val: Val;

}

};

Int I =-42;

Abdint absobj;

Unsigned int UI = absobj (I); // callabout absint: Operator (INT)

The function call operator must be declared as a member function. We can still "call" this object to run the overload call operator defined by the absobj object, this operator accepts an int value and returns its absolute value. Function call operators must be defined as member functions and can be overloaded.

 

Function objects are used for standard library algorithms,

Bool gt6 (const string & S)

{

Return S. Size ()> = 6;

}

Vector <string >:: size_type WC = count_if (words. Begin (), words. End (), gt6 );

Use gt6 as the pass to count_if
Calculate the number of words that make gt6 return true.

Class gt_cls

{

Public:

Gt_cls (size_t val = 0): bound (Vala ){}

Bool operator () (const string & S)

{

Return S. Size ()> = bound;

}

PRIVATE:

STD: String: size_type Blund;

};

Count_if (words. Begin (), words. End (), gt_cls (6) // test the number of characters with a length greater than 6.

 

Function objects defined in the standard library

Arithmetic function object type

+-*/Plus <type>

Relational function object type

=! ==>=<<=

Logical function object type

& |!

All of the above have been defined as a template class, which can be used as a function object during instantiation.

In the original definition, the function object is an object with behavior similar to the function, and the object is an instance of the class ..

Related Article

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.