不破不立

码农一枚

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  75 随笔 :: 0 文章 :: 12 评论 :: 22万 阅读

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
复制代码

 

posted on   jackjoe  阅读(5618)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
levels of contents
点击右上角即可分享
微信分享提示