Code Snippets/Boost2010. 9. 3. 15:44
코드의 미묘한 중복을 줄이는데 템플릿만한 것이 없다고 생각한다.
보통 아래와 같은 패턴을 가진 함수들... 즉 Value와 Data의 타입이 다르지만 뭔가 동일한 루틴을 가진 함수들...
이런 함수들이 여러개 있다면, 주저 없이 boost::bind를 사용해서 중복을 줄여보자.
( STL의 bind도 가능하지만, mem_fun에서 받을 수 있는 인자는 1개 뿐인 반면 boost는 8개다 )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool Func( ValueType Value, DataType Data )
{  
    // 뭔가를 검사하는 작업
    if ( 0 < Data.a )
    {
        ASSERT( "Someting bad is gonna happen. -_- [%d]", Data.a );
        return false;
    }
     
    // 여러 함수에 걸쳐... 약간씩 다른 함수 호출
    Value = Creator();
     
    // 여러 함수에 걸쳐... 동일한 루틴들
    ++m_iMyCount;
    DoSomething();
     
    return true;
}



Code Snippet
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
int main()
{
    DataType1 D1;
    DataType2 D2;
    int Sum = 0;   
 
    bool bSuccess = false;
    bSuccess = Func( Sum, D1, boost::bind( boost::mem_fn( &MyManager::Sum2 ), &g_Manager, D1.a, D1.b ) );
    ShowResult( bSuccess, Sum, "Sum2가 template이 아니라면 간단히 호출 가능" );
 
    bSuccess = Func( Sum, D1, boost::bind( boost::mem_fn< int, MyManager, int, short >( &MyManager::Sum2 ), boost::ref( g_Manager ), D1.a, D1.b ) );
    ShowResult( bSuccess, Sum, "Sum2가 template이라면 mem_fn을 명시적으로 호출" );
 
    boost::function< int( int, short ) > mfSum2 = boost::bind( &MyManager::Sum2, &g_Manager, _1, _2 );
    bSuccess = Func( Sum, D1, boost::bind( mfSum2, D1.a, D1.b ) );
    ShowResult( bSuccess, Sum, "mem_fn을 바인드 시켜서, 나중에 인자와 함께 호출" );
 
    boost::function< int() > FtrFunc = boost::bind( boost::mem_fn< int, MyManager, int, short >( &MyManager::Sum2 ), &g_Manager, D1.a, D1.b );
    bSuccess = Func( Sum, D1, FtrFunc );
    ShowResult( bSuccess, Sum, "함수 자체를 funtion에 바인드도 가능" );
 
    boost::function< int() > FtrFunc2 = boost::bind( boost::mem_fn< int, MyManager, int, short, long >( &MyManager::Sum3 ), &g_Manager, D2.a, D2.b, D2.c );
    bSuccess = Func( Sum, D1, FtrFunc2 );
    ShowResult( bSuccess, Sum, "인자3개짜리가 필요할 때도 간편하게 사용" );
}

결과
(Result: 1 (Sum: 3 | Sum2가 template이 아니라면 간단히 호출 가능
(Result: 1 (Sum: 3 | Sum2가 template이라면 mem_fn을 명시적으로 호출
(Result: 1 (Sum: 3 | mem_fn을 바인드 시켜서, 나중에 인자와 함께 호출
(Result: 1 (Sum: 3 | 함수 자체를 funtion에 바인드도 가능
(Result: 1 (Sum: 6 | 인자3개짜리가 필요할 때도 간편하게 사용

'Code Snippets > Boost' 카테고리의 다른 글

함수 호출 연기 & 함수 타입 캐스팅  (0) 2010.09.17
Nested Bind  (0) 2010.09.09
Generalized Function Pointers  (0) 2010.09.06
boost 관련 유용한 링크 모음  (0) 2010.08.20
Boost Thread  (0) 2010.08.20
Posted by codevania