Boost.Bind 访问 std::for_each 中的 std::map 元素
我有一个地图,其中存储了一个带有键的简单结构.struct 有两个成员函数,一个是 const,另一个不是.我已经成功地使用 std::for_each 调用了 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 成员函数的调用工作正常,但似乎 boost 内部期望在某处使用 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.
boostindmem_fn_template.hpp(151): error C2440: 'argument': 不能从 'const MyStruct *__w64 ' 转换为 'MyStruct *const '
boostindmem_fn_template.hpp(151): error C2440: 'argument' : cannot convert from 'const MyStruct *__w64 ' to 'MyStruct *const '
我很感激有关如何正确设置模板参数的任何帮助,因此 bind 确实可以正确识别参数并让我调用非 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(向下滚动到 //数据成员支持
部分),您会看到它将 result_type 类型定义为 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 的返回类型推导机制.因此,一个解决方案将明确告诉 Bind 结果不是 const:
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)
)
);
相关文章