繁体   English   中英

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

[英]boost::bind and insert of a boost::unordered_map

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

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

问题是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);};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM