2009-12-14 34 views
1

如何獲得boost :: bind以使用數組下標?這是我想要實現的。請指教。使用boost :: bind輸出作爲數組下標

[servenail:C++ progs的] $克++ -v
從/usr/lib/gcc/i386-redhat-linux/3.4.6/specs
閱讀規格與被配置:../configure - 前綴=/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: 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

是的,我知道綁定返回一個函數對象的事實。我以這種方式編寫了我的原始代碼,以使我的目標明確。我希望如果這可以實現而不需要調用一個單獨的函數。我猜不會。 – posharma 2009-12-14 19:38:22

1

您的代碼無法編譯的原因是因爲boost::bind的返回值是而不是可以用作數組下標的整數類型。而是,boost::bind返回未指定類型的實現定義的函數對象,可以使用()運算符調用該對象。

相關問題