1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <iostream>
#include <functional>
#include <iomanip>
#include <memory>
struct A
{
int member_fun( int a, int b, int c ) const
{
std::cout << "A::member_fun( " << a << ", " << b << ", " << c << " )\n" ;
return a + b + c + v ;
}
int v = 5 ;
};
long non_member_fun( const A& object, double a, char b, short c )
{
std::cout << "non_member_fun( " << a << ", " << +b << ", " << c << " )\n" ;
return a + b + c + object.v ;
}
struct functor
{
double operator() ( const A* object, double a, double b, double c ) const
{
std::cout << "functor::operator() ( " << a << ", " << b << ", " << c << " )\n" ;
return a + b + c + object->v ;
}
};
const auto closure = [] ( const A* object, unsigned short a, long long b, wchar_t c ) -> unsigned long long
{
std::cout << "closure( " << a << ", " << b << ", " << +c << " )\n" ;
return a + b + c + object->v ; ;
};
int main()
{
using namespace std::placeholders ;
A a ;
std::function< int(int,int,int) > call_wrapper ;
// pass wrapped reference to object
const auto fn = std::bind( &A::member_fun, std::ref(a), _2, _3, _1 ) ;
fn( 1, 2, 3 ) ; // A::member_fun( 2, 3, 1 )
// pass copy of object
std::bind( &A::member_fun, a, _2, _3, _1 )( 1, 2, 3 ) ; // A::member_fun( 2, 3, 1 )
call_wrapper = fn ;
call_wrapper( 1, 2, 3 ) ; // A::member_fun( 2, 3, 1 )
call_wrapper = std::bind( non_member_fun, std::ref(a), _3, _2, _1 ) ;
call_wrapper( 1, 2, 3 ) ; // non_member_fun( 3, 2, 1 )
call_wrapper = std::bind( functor(), std::addressof(a), _3, _1, _2 ) ;
call_wrapper( 1, 2, 3 ) ; // functor::operator() ( 3, 1, 2 )
call_wrapper = std::bind( closure, std::addressof(a), _1, _3, _2 ) ;
call_wrapper( 1, 2, 3 ) ; // closure( 1, 3, 2 )
const auto fn2 = std::bind( call_wrapper, _1, _1, _1 ) ;
fn2(4) ; // closure( 4, 4, 4 )
// pass smart pointer to object
std::function< void(short,double) > fn3 = std::bind( &A::member_fun, std::make_shared<A>(), _1, 99, _2 ) ;
fn3(4,5) ; // A::member_fun( 4, 99, 5 )
}
| |