cqd*_*234 2 c++ boost bind blitz++
我试着boost::bind用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;
}
Run Code Online (Sandbox Code Playgroud)
那么,我该怎么做呢?
谢谢!
提升版本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;
}
Run Code Online (Sandbox Code Playgroud)
我的编译命令是:g ++ t.cpp -I path/include/-std = c ++ 11 -L path/lib/-l blitz
resize可能是一个重载函数(在C++ 11中它必须是)所以你需要告诉编译器你想要的重载.对于一个参数形式,这应该适用于C++ 11:
bind(static_cast<void (type::*)(type::size_type)>(&type::resize), _1, 2)(a);
Run Code Online (Sandbox Code Playgroud)
或者更可读:
typedef void (type::*resize_signature)(type::size_type);
bind(static_cast<resize_signature>(&type::resize), _1, 2)(a);
Run Code Online (Sandbox Code Playgroud)
如果它不是一个重载函数(与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);
Run Code Online (Sandbox Code Playgroud)
不幸的是,这个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);
Run Code Online (Sandbox Code Playgroud)
或者在C++ 11中只使用lambda表达式而不是bind:
auto resize = [](type& v) { v.resize(2); };
resize(a);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |