2009-12-14 8 views
1

어떻게 boost :: bind를 배열 첨자로 사용할 수 있습니까? 여기 내가 성취하려고하는 것이있다. 제발 조언.boost :: bind 출력을 배열 첨자로 사용하기

[servenail : C++의 progs] $ g ++ -v로 구성 /usr/lib/gcc/i386-redhat-linux/3.4.6/specs
에서
읽기 사양 : ../configure - 접두어 =/usr --mandir =/usr/share/man --infodir =/usr/share/info - 사용 가능 공유 - 사용 가능 스레드 = posix - 사용 불가 검사 --with-system-zlib - enable -__ cxa_atexit --disable-libunwind-exceptions --enable-java-awt = gtk --host = i386-redhat-linux
스레드 모델 : posix
gcc 버전 3.4.6 20060404 (Red Hat 3.4.6-3)

[servenail: C++Progs]$ cat t-array_bind.cpp

#include <map> 
#include <string> 
#include <algorithm> 
#include <boost/lambda/lambda.hpp> 
#include <boost/lambda/bind.hpp> 
#include <iostream> 

using namespace std; 
using namespace boost; 
using namespace boost::lambda; 

class X 
{ 
public: 
    X(int x0) : m_x(x0) 
    { 
    } 

    void f() 
    { 
     cout << "Inside function f(): object state = " << m_x << "\n"; 
    } 

private: 
    int m_x; 
}; 

int main() 
{ 
    X x1(10); 
    X x2(20); 
    X* array[2] = {&x1, &x2}; 

    map<int,int> m; 
    m.insert(make_pair(1, 0)); 
    m.insert(make_pair(2, 1)); 

    for_each(m.begin(), 
      m.end(), 
      array[bind(&map<int,int>::value_type::second, _1)]->f()); 
} 

[servenail: C++Progs]$ g++ -o t-array_bind t-array_bind.cpp t-array_bind.cpp: In function `int main()': t-array_bind.cpp:40: error: no match for 'operator[]' in
'array[boost::lambda::bind(const Arg1&, const Arg2&) [with Arg1 = int std::pair::*, Arg2 = boost::lambda::lambda_functor >](((const boost::lambda::lambda_functor >&)(+boost::lambda::::_1)))]'

고마워요.

답변

1

Charles가 설명한대로 boost :: bind는 정수가 아닌 함수 개체를 반환합니다. 함수 객체는 각 멤버에 대해 평가됩니다.

struct get_nth { 
    template<class T, size_t N> 
    T& operator()(T (&a)[N], int nIndex) const { 
     assert(0<=nIndex && nIndex<N); 
     return a[nIndex]; 
    } 
} 

for_each(m.begin(), 
     m.end(), 
     boost::bind( 
      &X::f, 
      boost::bind( 
       get_nth(), 
       array, 
       bind(&map<int,int>::value_type::second, _1) 
      ) 
     )); 

편집 : 약간의 도우미 구조체는 문제를 해결할 나는 배열의 n 번째 요소를 반환하는 펑터를 변경했습니다.

+0

예, 저는 bind가 함수 객체를 반환한다는 사실을 알고 있습니다. 내 목표를 분명히하기 위해 원래 코드를 이런 식으로 작성했습니다. 나는 이것이 별도의 함수 호출없이 이루어질 수 있다면 좋겠다. 나는 그렇지 않다. – posharma

1

코드가 컴파일되지 않는 이유는 boost::bind의 반환 값이 이 아니기 때문에은 배열 첨자로 사용할 수있는 정수 유형이기 때문입니다. 오히려 boost::bind() 연산자를 사용하여 호출 할 수있는 지정되지 않은 유형의 구현 정의 함수 객체를 반환합니다.

관련 문제