boost :: bind和insert :: boost :: unordered_map

时间:2012-03-08 17:37:35

标签: c++ boost-bind boost-function

我想使用boost::bind创建boost::function将新的键值对插入boost::unoredered_map,但我收到的编译错误很少。

typedef boost::unordered_map< 
        std::string, std::string > dict_type;


inline void insert( const std::string& key, const std::string& value ){

    typedef std::pair<dict_type::iterator, bool> out_type;

    dict_type::value_type to_insert(key,value);

    boost::function<void()> f = boost::bind<out_type>( 
        &dict_type::insert
        ,obj_
        ,boost::cref(to_insert)
    );
}

以下错误似乎bind找不到unordered_map::insert的正确重载。在这种情况下,我指定了正确的重载,但这次它不起作用。你知道它是什么吗?

 ../include2/llve_clorder_id.h:32: error: no matching function for call to 
'bind(<unresolved overloaded function type>,
 boost::unordered_map<std::basic_string<char, std::char_traits<char>, 
 std::allocator<char> >, std::basic_string<char, std::char_traits<char>, 
 std::allocator<char> >, boost::hash<std::basic_string<char, std::char_traits<char>,   
 std::allocator<char> > >, std::equal_to<std::basic_string<char, std::char_traits<char>, 
 std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, 
 std::char_traits<char>, std::allocator<char> >, std::basic_string<char, 
 std::char_traits<char>, std::allocator<char> > > > >&, const 
 boost::reference_wrapper<const std::pair<const std::basic_string<char, 
 std::char_traits<char>, std::allocator<char> >, std::basic_string<char, 
 std::char_traits<char>, std::allocator<char> > > >)'

2 个答案:

答案 0 :(得分:1)

http://www.boost.org/doc/libs/1_49_0/libs/bind/bind.html#Troubleshooting建议您有时可以通过将指向成员函数的指针强制转换为所需类型来解决重载函数的问题。使用临时变量来阻止它变得完全不可读,它看起来像:

typedef std::pair<typename dict_type::iterator, bool> out_type;

typename dict_type::value_type to_insert(key,value);

out_type (dict_type::*ins) (typename dict_type::value_type const&) const = &dict_type::insert;

boost::function<void()> f = boost::bind(
    ins
    ,obj_
    ,boost::cref(to_insert)
);

答案 1 :(得分:1)

问题是boost::unordered_map包含多个insert,因此&dict_type::insert不明确。最简单的解决方案是定义一个函数来调用正确的重载:

void insert(dict_type & dict, dict_type::value_type const & value) {
    dict.insert(value);
}

boost::function<void()> f = boost::bind( 
    insert
    ,boost::ref(obj_)
    ,boost::cref(to_insert)
);

或者您可以明确指定过载:

boost::function<void()> f = boost::bind( 
    static_cast<out_type (dict_type::*)(dict_type::value_type const &)>(&dict_type::insert)
    ,obj_
    ,boost::cref(to_insert)
);

在C ++ 11中,您可以避免使用lambda:

的问题
std::function<void()> f = [&](){obj_.insert(to_insert);};
相关问题