unary_function和binary_function详解

unary_function和binary_function详解1 unary function 1 1 unary function 介绍 unary funciton 可以作为一个一元函数对象 又叫仿函数 的基类 它只定义了参数和返回值的类型 本身并不重载 操作符 这个任务交给派生类去完成 1 2

大家好,我是讯享网,很高兴认识大家。

1. unary_function

1.1 unary_function介绍

        unary_funciton可以作为一个一元函数对象(又叫仿函数)的基类,它只定义了参数和返回值的类型,本身并不重载()操作符,这个任务交给派生类去完成。

1.2 unary_function源码

//TEMPLATE STRUCT unary_function template<class _Arg, class _Result> struct unary_function { //base class for unary functions typedef _Arg argument_type; typedef _Result result_type; };
讯享网
成员类型 定义 注释
argument_type 第一个模板参数(Arg) ()重载函数的参数类型
result_type 第二个模板参数(Result) ()重载函数的返回值类型

 1.3 unary_function例子

讯享网//unary_function example #include <iostream> // std::cout, std::cin #include <functional> // std::unary_function //判断输入数据是否为Odd奇数?偶数是Even struct IsOdd : public std::unary_function<int,bool> { bool operator() (int number) {return (number%2!=0);} }; int main () { IsOdd IsOdd_object; IsOdd::argument_type input; IsOdd::result_type result; std::cout << "Please enter a number: "; std::cin >> input; result = IsOdd_object (input); std::cout << "Number " << input << " is " << (result?"odd":"even") << ".\n"; return 0; }

2. binary_function

2.1 binary_function介绍

        binary_function可以作为一个二元函数对象的基类,它只定义了参数和返回值的类型,本身并不重载()操作符,这个任务交给派生类去完成。

2.2 binary_function源码

//TEMPLATE STRUCT binary_function template<class _Arg1, class _Arg2, class _Result> struct binary_function { //base class for binary functions typedef _Arg1 first_argument_type; typedef _Arg2 second_argument_type; typedef _Result result_type; };
成员类型 定义 注释
first_argument_type 第一个模板参数(First_Arg) ()重载函数的第一个参数类型
second_argument_type 第二个模板参数(Second_Arg) ()重载函数的第二个参数类型
result_type 第三个模板参数(Result) ()重载函数的返回值类型

 2.3 binary_function例子

讯享网//binary_function example #include <iostream> // std::cout, std::cin #include <functional> // std::binary_function //比较两个数的大小 struct Compare : public std::binary_function<int,int,bool> { bool operator() (int a, int b) {return (a==b);} }; int main () { Compare Compare_object; Compare::first_argument_type input1; Compare::second_argument_type input2; Compare::result_type result; std::cout << "Please enter first number: "; std::cin >> input1; std::cout << "Please enter second number: "; std::cin >> input2; result = Compare_object (input1,input2); std::cout << "Numbers " << input1 << " and " << input2; if (result) { std::cout << " are equal.\n"; } else { std::cout << " are not equal.\n"; } return 0; }

小讯
上一篇 2025-03-03 13:38
下一篇 2025-03-28 07:31

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/100315.html