您的位置:首页 > 编程语言 > C语言/C++

function-like classes 仿函数笔记----C++学习之路

2017-11-07 22:09 288 查看
  1.本次笔记只提如何实现仿函数。

  2.函数是怎么样的呢,有函数名称,还有一个小括号,叫做函数调用操作符。如果有个东西能用到这个函数调用

操作符,那么就叫做他为函数,或者仿函数。

  3.代码实例:

template<class T>
struct identity
{
const T& operator() ( const T& x) const { return x; }
};

template <class Pair>
struct select1st
{
const typename Pair::first_type& operator() (const Pair& x) const { return x.first; }
};

template <class Pair>
struct select2nd
{
const typename Pair::second_type& operator()(const Pair& x) const { return x.second; }
};看看Pair:
template <class T1, class T2>
struct pair
{
T1 first;
T2 second;
pair():first(T1()), second(T2()){}
pair(const T1& a,const T2& b)
:first(a),second(b) {}
.....
};这里的T1和T2都可以不一样。
再来看看这个function like,如果看到类的操作符重载operator()大部分都是为了让自己function like。

这种类做出来的对象叫做函数对象,又成为仿函数。

  4.但是在3中的例子其实是不完整的代码,他们都继承了一个类unary_function。

以及在标准库中的plus也是仿函数,继承的是binary_function。

看下代码:

template <class Arg, class Result>
struct unary_function
{
typedef Arg argument_type;
typedef Result result_type;
};

template <class Arg1, class Arg2, class Result>
struct binary_function
{
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};这两个类的大小都是为0.但是如果在代码上,用sizeof来找,它实际上却是1.

  5.这次的笔记主要告诉自己,在标准库中有很多仿函数,这些仿函数都会继承一些奇怪的父类,这些
父类大小都为0.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: