我需要将map
的索引(std::wstring
及其值也是std::wstring
)传递给成员函数,该函数需要3 std::wstrings
作为参数。
我正在尝试使用boost::bind
中write
方法中的class Result
,如下面的示例代码所示。
我更清晰地重新发布代码,并且出现编译错误。
typedef std::map<std::wstring,std::wstring> map_type;
class Print
{
public:
Print(){};
virtual ~Print(){};
void setValue(const std::wstring & str1, const std::wstring & str2,
const std::wstring & str3 = L"")
{
wprintf(L"String1[%ls] String2[%ls] String3[%ls]\n",str1.c_str(), str2.c_str(), str3.c_str());
}
};
class Result : public Print
{
public:
Result(){};
virtual ~Result(){};
void write(const std::wstring val1, const std::wstring val2, const std::wstring val3)
{
std::map<std::wstring,std::wstring> my_map_test;
my_map_test[L"Idx1"]=L"Value1";
my_map_test[L"Idx2"]=L"Value2";
for_each(my_map_test.begin(), my_map_test.end(),
boost::bind(&Result::setValue,
boost::bind(&map_type::value_type::first,_1),
boost::bind(&map_type::value_type::second,_1), L"TEST"));
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Result result;
result.write();
return 0;
}
感谢。
答案 0 :(得分:0)
您的typedef
似乎并不完全正确。除此之外,您似乎在每个嵌套的bind()
表达式后都缺少一个括号。似乎Data::setValue
是一个成员函数,即它还需要被赋予它要应用的对象。也就是说,我认为你想这样使用它:
std::for_each(mem_ptr->properties.m_properties_map.begin(),
mem_ptr->properties.m_properties_map.end(),
boost::bind(&Data::setValue,
boost::ref(object),
boost::bind(&map_type::value_type::first, _1),
boost::bind(&map_type::value_type::second, _1),
L"Str"));
˙
可悲的是,我无法测试这确实会起作用,因为你只提供了部分代码。否则,使用合成扩展该对是一个有趣的想法。请注意,first
和second
也是std::pair<K, V>
的成员,但这些成员只能使用一个参数“调用”,即调用它们的对象。对于数据成员bind()
假装可以调用它们来相应地访问该值
答案 1 :(得分:0)
再次测试之后,它现在正常工作,使用boost :: bind时唯一缺少的参数就是“this”指针,如下所示
for_all(my_map_test, boost :: bind(&amp; Result :: setValue, this , 升压::绑定(安培; map_type :: VALUE_TYPE ::第一,_1), boost :: bind(&amp; map_type :: value_type :: second,_1),L“TEST”));