boost :: 출력을 배열 첨자로 바인딩합니다
문제
Boost :: 배열 첨자 작업을 위해 BIND를 얻으려면 어떻게해야합니까? 내가 달성하려는 것입니다. 조언을 해주세요.
servenail : c ++ progs] $ g ++ -v
/usr/lib/gcc/i386-redhat-linux/3.4.6/specs의 사양을 읽습니다
다음과 같이 구성 : ../configure ---prefix =/usr-mandir =/usr/share/man ---infodir =/usr/share/info --enable-shared-enable-threads = posix-disable-Checking -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 : 오류 :'운영자와 일치하지 않습니다. []' 안에
'배열 [boost :: lambda :: bind (const arg1 &, const arg2 &) : lambda_functor> &) (+boost :: lambda :::: _ 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 번째 요소를 반환하도록 functor를 변경했습니다.
다른 팁
코드가 컴파일하지 않는 이유는 반환 값이 boost::bind
~이다 ~ 아니다 배열 첨자로 사용할 수있는 정수 유형. 꽤, boost::bind
지정되지 않은 유형의 구현 정의 된 함수 개체를 반환하며,이 유형을 사용하여 호출 할 수 있습니다. ()
운영자.