函数对象

来源:互联网 发布:大型网页游戏源码 编辑:程序博客网 时间:2024/04/30 06:11

函数对象是类似于函数的对象,就是具有operator()的对象


#include <algorithm>#include <iostream>using namespace std;void test(int i){    cout << "hello: " << i << endl;}class funobj{    const char *m_msg;public:    funobj(const char *msg) : m_msg(msg) {}    void operator()(int i)    {        cout << m_msg << ": " << i << endl;    }};template <typename Iter, typename UnarFunc>void myfor_each(Iter begin, Iter end, UnarFunc fun){    while (begin != end) {        fun(*begin);        //fun.operator()(*begin);        ++begin;    }}int main(int argc, char* argv[]){     int a[5] = {0, 1, 2, 3, 4};     // for_each(a, a+5, test);     // for_each(a, a+5, funobj<int>("jjdd"));     myfor_each(a, a+5, test);     funobj obj = funobj("jjdd");     myfor_each(a, a+5, obj);     return 0;}


0 0
原创粉丝点击