C++ 11之std::bind用法
生活随笔
收集整理的這篇文章主要介紹了
C++ 11之std::bind用法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#include <iostream>
#include <functional>
#include <stdio.h>
int funcA( int a, int b )
{
return a + b;
}
int funcB( int &a, int &b )
{
++a;
return a + b;
}
class C
{
public:
int funcC( int a, int b ) {
return a + b;
}
};
int main(int argc, char *argv[])
{
// 綁定一個普通函數(shù),傳遞的參數(shù)為1、2
auto fn0 = std::bind( funcA, 1, 2 );
std::cout << fn0() << std::endl; // 3
// 綁定一個普通函數(shù),第一個參數(shù)為占位符(用于調(diào)用時傳參),第二個參數(shù)為3
auto fn1 = std::bind( funcA, std::placeholders::_1, 3 );
std::cout << fn1( 1 ) << std::endl; // 4
// 占位符是引用傳遞,第二個參數(shù)為值傳遞(雖然funcB的2個參數(shù)都為引用)
auto a = 1;
auto b = 1;
auto fn2 = std::bind( funcB, std::placeholders::_1, b );
std::cout << fn2( a ) << std::endl; // 3
std::cout << a << std::endl; // 2 引用傳遞
std::cout << b << std::endl; // 1 值傳遞
// 綁定一個類的實例函數(shù),傳遞的參數(shù)為1、2
C c;
auto fn3 = std::bind( &C::funcC, c, 1, 2 );
std::cout << fn3() << std::endl; // 3
// 綁定一個類的實例函數(shù),參數(shù)為占位符,返回值為函數(shù)類型
std::function<int(int,int)> fn4 = std::bind( &C::funcC, c, std::placeholders::_1, std::placeholders::_2 );
std::cout << fn4( 1, 2 ) << std::endl; // 3
system( "pause" );
return 0;
}
總結(jié)
以上是生活随笔為你收集整理的C++ 11之std::bind用法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中材节能属于什么概念股票 主要业务都有
- 下一篇: ChatMoney是你创业自由副业的pl