0

我想用来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> > > >)'
4

2 回答 2

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)
);
于 2012-03-08T18:31:21.977 回答
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);};
于 2012-03-08T18:39:24.100 回答