使用 boost :: 绑定将映射作为参数传递



我需要将map的索引(这是一个std::wstring及其值也是一个std::wstring)传递给一个以 3 std::wstrings作为参数的成员函数。我正在尝试在class Resultwrite 方法中使用 boost::bind,如下面的示例代码所示。

我正在更清晰地重新发布代码,并且出现编译错误。

    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;
}

谢谢。

看来你的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"));

̇可悲的是,我无法测试这是否确实有效,因为您只提供了部分代码。否则,使用组合扩展货币对是一个有趣的想法。请注意,firstsecond 也是 (std::pair<K, V> 的成员),但这些成员只能使用一个参数来"调用",即调用它们的对象。对于数据成员bind()假装可以相应地调用它们来访问值

再次测试后,它现在可以工作了,使用 boost::bind 时唯一缺少的参数是"this"指针,如下所示

for_all(my_map_test, boost::bind(&Result::setValue, this, boost::bind(&map_type::value_type::first,_1), boost::bind(&map_type::value_type::秒,_1),L"测试"));

相关内容

最新更新