unary_function和binary_function詳解


1.unary_function和binary_function介紹

1.1 unary_function介紹

  unary_function可以作為一個一元函數對象基類,它只定義參數返回值的類型,本身並不重載()操作符,這個任務應該交由派生類去完成。

1.2 unary_function源碼

1 template <class Arg, class Result>
2   struct unary_function {
3     typedef Arg argument_type;
4     typedef Result result_type;
5   };

 

成員類型 定義 注釋
argument_type 第一個模板參數 (Arg) ()重載函數的參數類型
result_type 第二個模板參數(Result) ()重載函數的返回值類型

 

1.3 例子

 1 // unary_function example
 2 #include <iostream>     // std::cout, std::cin
 3 #include <functional>   // std::unary_function
 4 
 5 struct IsOdd : public std::unary_function<int,bool> {
 6   bool operator() (int number) {return (number%2!=0);}
 7 };
 8 
 9 int main () {
10   IsOdd IsOdd_object;
11   IsOdd::argument_type input;
12   IsOdd::result_type result;
13 
14   std::cout << "Please enter a number: ";
15   std::cin >> input;
16 
17   result = IsOdd_object (input);
18 
19   std::cout << "Number " << input << " is " << (result?"odd":"even") << ".\n";
20 
21   return 0;
22 }
View Code

 2. binary_function介紹

2.1 binary_function介紹

  binary_function可以作為一個元函數對象基類,它只定義參數返回值的類型,本身並不重載()操作符,這個任務應該交由派生類去完成。

2.2 binary_function源碼

1 template <class Arg1, class Arg2, class Result>
2   struct binary_function {
3     typedef Arg1 first_argument_type;
4     typedef Arg2 second_argument_type;
5     typedef Result result_type;
6   };

 

成員類型 定義 注釋
first_argument_type 第一個模板參數(Arg1) ()重載函數的第一個參數類型
second_argument_type 第一個模板參數 (Arg2) ()重載函數的第二個參數類型
return_type 第一個模板參數(Result) ()重載函數的返回值類型

2.3 例子

 1 // binary_function example
 2 #include <iostream>     // std::cout, std::cin
 3 #include <functional>   // std::binary_function
 4 
 5 struct Compare : public std::binary_function<int,int,bool> {
 6   bool operator() (int a, int b) {return (a==b);}
 7 };
 8 
 9 int main () {
10   Compare Compare_object;
11   Compare::first_argument_type input1;
12   Compare::second_argument_type input2;
13   Compare::result_type result;
14 
15   std::cout << "Please enter first number: ";
16   std::cin >> input1;
17   std::cout << "Please enter second number: ";
18   std::cin >> input2;
19 
20   result = Compare_object (input1,input2);
21 
22   std::cout << "Numbers " << input1 << " and " << input2;
23   if (result)
24       std::cout << " are equal.\n";
25   else
26       std::cout << " are not equal.\n";
27 
28   return 0;
29 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM