Question

Comment puis-je obtenir boost :: bind de travailler avec des indices de tableau? Voici ce que je suis en train de réaliser. S'il vous plaît conseiller.

[servenail: C ++ Progs] $ g ++ -v
Lecture de spécifications /usr/lib/gcc/i386-redhat-linux/3.4.6/specs
Configuré avec: ../configure --prefix = / usr --mandir = / usr / share / man --infodir = / usr / share / info --enable-shared --enable-threads = posix --disable-vérification --with-system-zlib --enable -__ cxa_atexit --disable-libunwind-exceptions --enable-java-AWT = gtk --host = i386- redhat-linux
Modèle du fil: posix
gcc version 3.4.6 20.060.404 (Red Hat 3.4.6-3)

  

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

#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: En fonction `int main () ':       t-array_bind.cpp: 40: Erreur: aucune correspondance pour 'opérateur []'
  « Tableau [boost :: lambda :: bind (const   Arg1 &, const & Arg2) [avec arg1 = int   std :: paire :: *, arg2 =   boost :: lambda :: lambda_functor>] (((boost :: lambda const :: lambda_functor> &) (+ boost :: lambda :::: _ 1)))]

Merci beaucoup.

Était-ce utile?

La solution

Comme Charles l'a expliqué, boost :: bind renvoie un objet de fonction et non pas un nombre entier. L'objet de la fonction sera évaluée pour chaque membre. Un peu struct aide va résoudre le problème:

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) 
             )
         ));

Edit: J'ai changé le foncteur de retourner l'élément n-ième du tableau.

Autres conseils

La raison pour laquelle votre code ne compile pas parce que la valeur de retour de boost::bind est pas un type entier qui peut être utilisé comme un indice de tableau. Au contraire, boost::bind retourne un objet de fonction définie par l'implémentation d'un type quelconque, qui peut être appelé en utilisant l'opérateur ().

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top