日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

函数指针amp;绑定: boost::functoin/std::function/bind

發布時間:2023/11/27 生活经验 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 函数指针amp;绑定: boost::functoin/std::function/bind 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

see link: https://isocpp.org/wiki/faq/pointers-to-members
function vs template: http://stackoverflow.com/questions/14677997/stdfunction-vs-template

boost::functoin/std::function可用于全部 operator() 操作的對象(函數,類。成員函數。lambda表達式等等)。

用處就是能夠使用一個函數指針調用不用的函數實體(僅僅要他們的signature一樣),實現回調函數。或者多種不同的算法等等。
關于 std::function的實現。 see link:http://stackoverflow.com/questions/18453145/how-is-stdfunction-implemented
非常好的樣例:原文鏈接

#include <functional>
#include <iostream>
using namespace std;std::function< int(int)> Functional;// 普通函數
int TestFunc(int a)
{return a;
}// Lambda表達式
auto lambda = [](int a)->int{ return a; };// 函數對象(functor)
class Functor
{
public:int operator()(int a){return a;}
};// 1.類成員函數
// 2.類靜態函數
class TestClass
{
public:int ClassMember(int a) { return a; }static int StaticMember(int a) { return a; }
};int main()
{// 普通函數Functional = TestFunc;int result = Functional(10);cout << "普通函數:"<< result << endl;// Lambda表達式Functional = lambda;result = Functional(20);cout << "Lambda表達式:"<< result << endl;// 仿函數Functor testFunctor;Functional = testFunctor;result = Functional(30);cout << "仿函數:"<< result << endl;// 類成員函數TestClass testObj;Functional = std::bind(&TestClass::ClassMember, testObj, std::placeholders::_1);result = Functional(40);cout << "類成員函數:"<< result << endl;// 類靜態函數Functional = TestClass::StaticMember;result = Functional(50);cout << "類靜態函數:"<< result << endl;return 0;
}

function簡化了函數指針的使用:

class FooClass {
public:void Print( int a ) {std::cout << "A FooClass, param = "<< a <<" this = " << this << std::endl;}
};void main() {FooClass *myFoo = new FooClass();void( FooClass::* oldFunc )(int) = &FooClass::Print; //C style function pointer(myFoo->*oldFunc)( 5 );boost::function newFunc = boost::bind( &FooClass::Print, myFoo, _1 ); //boost function      newFunc( 5 );
}

轉載于:https://www.cnblogs.com/mengfanrong/p/5186058.html

總結

以上是生活随笔為你收集整理的函数指针amp;绑定: boost::functoin/std::function/bind的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。