8.2(목) C++ - 바인더( binder )

from Study/C++ 2007/08/02 20:36 view 17944
// 바인더를 구현해보기.

template<class Arg1, class Arg2, class Result> struct xbinary_function
{
    typedef Arg1 first_argument_type;
    typedef Arg2 second_argument_type; typedef Result result_type;
};

class AbsolutePlus : public xbinary_function< int, int, int >
{
public:
    int operator ()(int a, int b) const
    {
        return abs(a) + abs(b);
    }
};

template<typename T> class my_binder1nd
{
    T op;
    typename T::first_argument_type left;
public:
    my_binder1nd( T _right, typename T::first_argument_type _left )
        : op(_right), left(_left) {}
    typename T::result_type operator()
        ( typename T::first_argument_type right ) const
    {
        return op( left, right );
    }
};

template<typename T> class my_binder2nd
{
    T op;
    typename T::second_argument_type right;
public:
    my_binder2nd( T _left, typename T::second_argument_type _right)
        : op(_left), right(_right) {}
    typename T::result_type operator()
        ( typename T::first_argument_type left ) const
    {
        return op( left, right );
    }
};

void main()
{
    // 1번째파라미터를상수값으로고정
    my_binder1nd<AbsolutePlus> f1( AbsolutePlus(), 2 ); 
    // 2번째파라미터를상수값으로고정
    my_binder2nd<AbsolutePlus> f2( AbsolutePlus(), 5 );

    cout << f1(-3) << endl;
    cout << f2(-5) << endl;
}







//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////


















// 바인더



// 단항함수: 인자가 1개인 함수.
// 이항함수: 인자가 2개인 함수

int foo( int a )
{
    return a % 3 == 0;
}

void main()
{
    // STL에는 modulus가 있다.
    modulus<int> m;
    int k = m(10, 3);
    cout << k << endl;

    int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


    // 함수버전으로 수행
    int* p = remove_if( x, x+10, bind2nd( m, 3 ) );

    // 이항함수 객체를 단항함수 객체로 변경한다. 클래스버전으로 수행.
    binder2nd<modulus<int> > f( m, 3 );   // f는 m%3을 가지는 단항함수이다.
    int k2 = f(10);
    cout << k2 << endl;
    int* p1 = remove_if( x, x + 10, f );  // 3의 배수가 아닌 것을 제거해라.

    //int* p = remove_if( x, x + 10, foo );
    copy( x, p1, ostream_iterator<int>( cout, " " ) );
}
Tag |

Trackback Address :: 이 글에는 트랙백을 보낼 수 없습니다