2

我尝试使用boost::bindwith std::vector<>::resize

但是下面的代码不会编译:

#include <boost/bind.hpp>
#include <vector>
using namespace boost;

int main(){
    typedef std::vector<double> type;
    type a;
    bind(&type::resize, _1, 2)(a);
    return 0;
}

那么,我该怎么做呢?

谢谢!

提升版本 1.53 gcc 版本 4.8 或 4.6

*编辑:*上面的代码适用于 -std=c++11。其实我原来的问题是这样的:

#include <boost/bind.hpp>
#include <blitz/array.h>
#include <vector>
using namespace boost;
using namespace blitz;

int main(){
    typedef Array<double, 1> type;
    type a;
            //a.resize(4) is ok;
    bind(&type::resize, _1, 2)(a);
    return 0;
}

我的编译命令是: g++ t.cpp -I path/include/ -std=c++11 -L path/lib/ -l blitz

4

1 回答 1

7

resize可能是一个重载函数(在 C++11 中它必须是),所以你需要告诉编译器你想要哪个重载。对于一个参数形式,这应该在 C++11 中工作:

bind(static_cast<void (type::*)(type::size_type)>(&type::resize), _1, 2)(a);

或者更具可读性:

typedef void (type::*resize_signature)(type::size_type);
bind(static_cast<resize_signature>(&type::resize), _1, 2)(a);

如果它不是重载函数(与 C++03 模式下的 GCC 一样),则它需要两个参数(一个具有默认值),并且您需要提供第二个参数,因为bind不能使用默认参数:

typedef void (type::*resize_signature)(type::size_type, const value_type&);
bind(static_cast<resize_signature>(&type::resize), _1, 2, 0.0)(a);

不幸的是,这个 C++03 版本不可移植,允许实现使用单个函数或一对重载。为了使其可移植,或与其他类型一起使用,例如Array您可以将调用包装在调用的自定义仿函数中resize,因此您不需要知道确切的签名:

typename<class VecT>
struct resizer<VecT> {
    void operator()(VecT& v, unsigned n) const { v.resize(n); }
};
// ...
bind(resizer<type>(), _1, 2)(a);

或者在 C++11 中只使用 lambda 表达式而不是bind

auto resize = [](type& v) { v.resize(2); };
resize(a);
于 2013-03-08T12:09:59.257 回答