CPP Templates 之 仿函數

來源:互聯網
上載者:User
// 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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.