C++ Primer 5th notes (chap 14 overload operation and type conversion) function call operator

1. Definition

If the class defines the call operator (the function call operator is overloaded), the object of this class is called a function object, and the object of this class can be used like a function.

eg.

struct absInt{
    
    
	int operator()(int val) const{
    
    
		return val < 0 ? -val : val;
	}
};

int i = -42;
absInt absObj;
int ui = absObj(i);	//i被传递给absObj.operator() 

2. Features

  • The function call operator must be defined as a member function.
  • . A class can define multiple different versions of the call operator, which must be different in the number or types of parameters.
  • . Classes with function call operators can also store state, so they are more flexible than ordinary functions.
  • . Function objects are often used as actual parameters of generic algorithms.
class PrintString
{
    
    
public:
    PrintString(ostream &o = cout, char c = ' '):
        os(o), sep(c) {
    
     }
    void operator()(const string &s) const
    {
    
    
        os << s << sep;
    }

private:
    ostream &os;   // stream on which to write
    char sep;      // character to print after each output
};
 
 string strText = "test";
 PrintString printer;  // uses the defaults; prints to cout
 printer(strText);     // prints s followed by a space on cout

  PrintString printer2(cerr, '_');
  printer2(strText);		//cerr中打印s,后面跟一个换行符
 
  //函数对象常常作为泛型算法的实参
  std::vector<string> vecStr = {
    
    "a1", "b1"};
  for_each(vecStr.begin(), vecStr.end(), PrintString(cerr, '-'));

Output result:

test test_a1-b1-

[Quote]

[1] Code functionObject.h

Guess you like

Origin blog.csdn.net/thefist11cc/article/details/114160509