【问题标题】:Using boost::bind output as an array subscript使用 boost::bind 输出作为数组下标
【发布时间】:2009-12-14 07:10:58
【问题描述】:

如何让 boost::bind 使用数组下标?这就是我想要实现的目标。请指教。

[servnail: 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:在函数“int main()”中: t-array_bind.cpp:40: 错误: 'operator[]' 不匹配
'数组[boost::lambda::bind(const Arg1&, const Arg2&) [与 Arg1 = int std::pair::*, Arg2 = boost::lambda::lambda_functor >](((const boost::lambda::lambda_functor >&)(+boost::lambda::::_1)))]'

非常感谢。

【问题讨论】:

    标签: c++ arrays boost bind subscript


    【解决方案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 个元素。

    【讨论】:

    • 是的,我知道 bind 返回一个函数对象的事实。我以这种方式编写了我的原始代码以明确我的目标。我希望这是否可以通过调用单独的函数来实现。我猜不是。
    【解决方案2】:

    您的代码无法编译的原因是因为boost::bind 的返回值不是可以用作数组下标的整数类型。相反,boost::bind 返回一个未指定类型的实现定义的函数对象,可以使用 () 运算符调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 2016-03-16
      • 2014-06-11
      • 1970-01-01
      相关资源
      最近更新 更多