CPP Templates 之 仿函数

// bolgcontent.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>

//仿函数

//一、函数指针和函数引用
//例如:

#include <typeinfo>

void foo()
{
    std::cout<<"foo() called"<<'\n';
}

typedef void FooT();//FooT 是一个函数类型


int _tmain(int argc, _TCHAR* argv[])
{
    foo();//直接调用

    std::cout<<"Types of foo:"<<typeid(foo).name()<<'\n';
    std::cout<<"Types of foo:"<<typeid(FooT).name()<<'\n';

    FooT *pf=foo;//隐式转型
    pf();//通过指针的间接调用
    (*pf)();//等价于pf()

    //输出pf的类型
    std::cout<<"Types of foo:"<<typeid(pf).name()<<'\n';

    FooT & rf=foo;//没有隐士转换
    rf();//通过引用的间接调用

    //输出rf的类型
    std::cout<<"Types of foo:"<<typeid(rf).name()<<'\n';

    return 0;
}

// bolgcontent.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>

//仿函数

//二、class类型的仿函数
//在cpp中,虽然函数指针就是现成的仿函数;然而在很多情况下,如果使用重载了函数调用
//运算符的class类型对象的话,可以给我们带来很多的好处:譬如灵活性、性能甚至两者兼
//备
//例如:

class ConstantIntFunctor
{
private:
    int value;//仿函数调用 所返回的值
public:
    ConstantIntFunctor(int c):value(c)
    {}

    //函数调用
    int operator() ()
    {
        return value;
    }
};

//使用上面函数对象的客户端函数
void client(ConstantIntFunctor & cif)
{
    std::cout<<"call back functor yields "<<cif()<<'\n';
}

int _tmain(int argc, _TCHAR* argv[])
{
    ConstantIntFunctor seven(7);
    ConstantIntFunctor fortytwo(42);

    client(seven);
    client(fortytwo);
    return 0;
}

posted on 2009-11-16 00:32  ATAK  阅读(328)  评论(0编辑  收藏  举报

导航