Boost.Bind访问的std :: for_each的性病::地图元素 [英] Boost.Bind to access std::map elements in std::for_each

查看:144
本文介绍了Boost.Bind访问的std :: for_each的性病::地图元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地图存储用钥匙一个简单的结构。该结构有两个成员函数,一个是const的其他没有。我已经成功使用std :: for_each的,没有任何问题调用const函数,但我有一些问题,调用非const函数。

I've got a map that stores a simple struct with a key. The struct has two member functions, one is const the other not. I've managed calling the const function using std::for_each without any problems, but I've got some problems calling the non-const function.

struct MyStruct {
  void someConstFunction() const;
  void someFunction();
};

typedef std::map<int, MyStruct> MyMap;
MyMap theMap;

//call the const member function
std::for_each(theMap.begin(), theMap.end(),
   boost::bind(&MyStruct::someConstFunction, boost::bind(&MyMap::value_type::second, _1)));

//call the non-const member function
std::for_each(theMap.begin(), theMap.end(),
   boost::bind(&MyStruct::someFunction, boost::bind(&MyMap::value_type::second, _1)));

到const成员函数调用工作正常,但似乎提振内部期望一个常量MYSTRUCT的地方,因而失败,并在MSVC7.1。

The call to the const member function works fine, but it seems boost internally expects a const MyStruct somewhere, and thus fails with the following compilation error in MSVC7.1.

升压\\绑定\\ mem_fn_template.hpp(151):错误C2440:'参数':无法从'常量MYSTRUCT * __ W64'转换为'MYSTRUCT * const的

boost\bind\mem_fn_template.hpp(151): error C2440: 'argument' : cannot convert from 'const MyStruct *__w64 ' to 'MyStruct *const '

我倒是AP preciate如何正确设置模板参数的任何帮助,所以不绑定正确识别参数,让我调用非const函数。

I'd appreciate any help on how to set the template parameters correctly, so bind does recognize the parameters correctly and let me call the non const function.

谢谢,
卡尔

推荐答案

IIRC,Boost.Bind使用的boost ::的mem_fn 其绑定到成员的能力。现在,如果你看一下 mem_fun (向下滚动到在 //数据成员的支持部分),你会看到它的typedef result_type的它作为一个const&安培;,而仍然有配套的提取函数调用操作符重载的从非const参数的非const成员。

IIRC, Boost.Bind uses boost::mem_fn for its binding to members capability. Now, if you look at mem_fun (scroll down to the // data member support part), you'll see that it typedefs its result_type as a const&, while is still has overloads of the function call operator supporting the extraction of a non-const member from a non-const argument.

因此​​,它看来,问题是,这种混淆Boost.Bind的返回类型推演机制。一种解决方案从而明确地告诉绑定的结果是不是常量:

It thus seems that the problem is that this confuses Boost.Bind's return type deduction mechanism. A solution would thus to explicitly tell Bind that the result is not const:

//call the non-const member function
std::for_each(theMap.begin(), theMap.end(),
   boost::bind(&MyStruct::someFunction, 
       boost::bind<MyStruct&>(&MyMap::value_type::second, _1)
   )
);

这篇关于Boost.Bind访问的std :: for_each的性病::地图元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆