我有一个映射,它存储一个带有键的简单结构。该结构有两个成员函数,一个是 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/