c++ - Boost.Bind 以访问 std::for_each 中的 std::map 元素

标签 c++ boost bind stdmap foreach

我有一个映射,它存储一个带有键的简单结构。该结构有两个成员函数,一个是 const,另一个不是。我已经设法使用 std::for_each 调用 const 函数而没有任何问题,但我在调用非 const 函数时遇到了一些问题。

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 成员函数的调用工作正常,但似乎 boost 内部期望某个地方有一个 const MyStruct,因此在 MSVC7.1 中出现以下编译错误而失败。

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

对于如何正确设置模板参数的任何帮助,我将不胜感激,因此 bind 确实可以正确识别参数并让我调用非 const 函数。

谢谢, 卡尔

最佳答案

IIRC,Boost.Bind 使用 boost::mem_fn 来绑定(bind)到成员的能力。现在,如果你看看 mem_fun (向下滚动到 //data member support 部分),您会看到它将其 result_type 类型定义为 const&,同时它仍然具有支持提取非-来自非常量参数的 const 成员。

因此看来问题是这混淆了 Boost.Bind 的返回类型推导机制。因此,一个解决方案将显式告诉 Bind 结果不是 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)
   )
);

关于c++ - Boost.Bind 以访问 std::for_each 中的 std::map 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2311752/

相关文章:

c++ - 如何修复 'Cannot assign requested address?'

c++ - 将 std::vector 分配给堆上特定内存位置的正确语法?

c++ - 当这些对象位于单独的共享库中时,如何向工厂自动注册 C++ 对象?

c++11 - std::bind 调用 std::make_shared

c++ - 将 std 绑定(bind)传递到函数映射的问题

c++ - 按值传递指针

c++ - 在 Windows 10 VS2015 上构建 Boost - 无法打开 *.lib

c++ - 保留从工厂 Create 方法返回的 shared_ptr 的最佳方法

c++ - 如何配置 boost::graph 以使用我自己的(稳定的)顶点索引?

javascript - famo.us/js : bind dynamic data to click event for emitting data