c++ - 使用 boost::bind 输出作为数组下标

标签 c++ arrays boost bind subscript

如何让 boost::bind 与数组下标一起工作?这就是我想要实现的目标。请指教。

[服务: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(红帽 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)))]'

非常感谢。

最佳答案

正如 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 个元素。

关于c++ - 使用 boost::bind 输出作为数组下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1899393/

相关文章:

c++ - 如何在QWidget中创建QToolBar?

用 C 比较两个数组

boost - 使用 boost::weak_ptr 打破循环依赖的示例

c++ - 如何获取有序非唯一 boost 多索引集的某些索引字段的唯一值

c++ - QSqlDatabasePrivate::addDatabase:重复的连接名称 'qt_sql_default_connection'

c++ - VS13 C++ 意外整数溢出

java - 数组列表超出范围

c++ - Boost Statechart - 本地转换

c++ - libcurl 和 DNS ttl 中的内部连接管理

python - Numpy 中的矢量化 - 广播