日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++中function的實現原理詳解_C 語言

作者:Hello_Bugs ? 更新時間: 2023-01-07 編程語言

前言

類模版std::function是一種通用、多態的函數封裝。std::function的實例可以對任何可以調用的目標實體進行存儲、復制、和調用操作,這些目標實體包括普通函數、Lambda表達式、函數指針、以及其它函數對象等。std::function對象是對C++中現有的可調用實體的一種類型安全的包裹(我們知道像函數指針這類可調用實體,是類型不安全的)。

通常std::function是一個函數對象類,它包裝其它任意的函數對象,被包裝的函數對象具有類型為T1, …,TN的N個參數,并且返回一個可轉換到R類型的值。std::function使用 模板轉換構造函數接收被包裝的函數對象;特別是,閉包類型可以隱式地轉換為std::function

自己實現function

#include <iostream>
#include <string>
using namespace std;

template<typename T>
class MyFunction3 {

};

template<typename Ty, typename A1>
class MyFunction3<Ty(A1)> {

public:
	typedef Ty(*pFunction)(A1);//定義一個函數指針,指針指向的函數返回類型是Ty,有1個函數參數
	MyFunction3<Ty(A1)>(pFunction _pFunction) : _function(_pFunction) {
	}

	Ty operator()(A1 arg1) {
		return (*_function)(arg1);
	}

private:
	pFunction _function;
};


template<typename Ty,typename A1,typename A2>
class MyFunction3<Ty(A1,A2)> {

public:

	typedef Ty(*pFunction)(A1, A2);//定義一個函數指針,指針指向的函數返回類型是Ty,有兩個函數參數
	MyFunction3<Ty(A1, A2)>(pFunction _pFunction):_function(_pFunction) {
	}
    
	Ty operator()(A1 arg1, A2 arg2) {
		return (*_function)(arg1, arg2);
	}

private:
	pFunction _function;
};


void showMes(string mes) {
	cout << "showMes(string mes)=" << mes << endl;
}


int sum1(int x, int y) {
	cout << "sum1 "<<(x+y) << endl;
	return x + y;
}
int sum2(int x, int y) {
	cout << "sum2 " << (x + y) << endl;
	return x + y;
}

int main() {

	MyFunction3<int(int, int)> f1(sum1);
	f1(20,30);


	MyFunction3<void(string)> f2(showMes);
	f2("AAAA");

	system("pause");
	return 0;
}

上面代碼我們實現了兩個模板的部分特例化

  • class MyFunction3<Ty(A1)> 一個函數參數的
  • class MyFunction3<Ty(A1,A2)> 兩個函數參數的

所以問題來了...三個參數,四個參數,五個參數等若干個參數的怎么辦?

可以使用C++11 可變參數類型, 具體如下

#include <iostream>
#include <string>
using namespace std;

template<typename T>
class MyFunction4 {

};


template<typename R , typename... A >
class MyFunction4<R(A...)> {

public:
	typedef R(*PFUNCTION)(A...);

	MyFunction4<R(A...)>(PFUNCTION _p) : function(_p) {}

	R operator()(A... arg) {
		return (*function)(arg...);
	}

private:

	PFUNCTION function;
};


void showMes1(string mes) {
	cout << "showMes(string mes)=" << mes << endl;
}

int sum11(int x, int y) {
	cout << "sum11 " << (x + y) << endl;
	return x + y;
}
int sum21(int x, int y) {
	cout << "sum21 " << (x + y) << endl;
	return x + y;
}

int main() {

	MyFunction4<int(int, int)> f1(sum11);
	f1(20, 30);


	MyFunction4<void(string)> f2(showMes1);
	f2("AAAA");

	system("pause");
	return 0;
}

原文鏈接:https://www.cnblogs.com/erichome/p/16965242.html

欄目分類
最近更新