1

配列の添え字を処理するために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 -例外--enable-java-awt=gtk --host = i386- redhat-linux
スレッドモデル:
posixgccバージョン3.4.620060404(Red Hat 3.4.6-3)

[servnail: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:関数 `int main()':t-array_bind.cpp:40:エラー:'演算子に一致しません[]'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)))] '

どうもありがとう。

4

2 に答える 2

1

コードがコンパイルされない理由は、の戻り値が配列の添え字として使用できる整数型でboost::bindないためです。むしろ、演算子boost::bindを使用して呼び出すことができる、指定されていないタイプの実装定義関数オブジェクトを返します。()

于 2009-12-14T10:28:45.543 に答える
1

チャールズが説明したように、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 番目の要素を返すようにファンクターを変更しました。

于 2009-12-14T10:44:43.030 に答える