zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    js异步编程思想【node的精华】
    python偏函数
    软工划水日报-安卓端侧部署(1) 4/23
    软工划水日报-模型预测 4/22
    软工划水日报-《构建之法》阅读笔记SONO.5 4/21
    软工划水日报-paddle模型训练(3) 4/20
    软工划水日报-paddle模型训练(2) 4/19
    软工划水日报-paddle模型训练(1) 4/18
    软工划水日报-CUDA下载与安装 4/17
    软工划水日报-AIchallager数据集下载及处理 4/16
  • 原文地址:https://www.cnblogs.com/bayonetxxx/p/1603584.html
Copyright © 2011-2022 走看看