【问题标题】:boost::bind with maps, what's the difference between binding std::pair and std::map::value_type?boost::bind 与映射,绑定 std::pair 和 std::map::value_type 有什么区别?
【发布时间】:2012-02-26 16:55:50
【问题描述】:

以下两种情况有什么区别?

std::pair<int,std::string> example_1 (std::make_pair (1,"foo"));
int value_1 = boost::bind (&std::pair<int,std::string>::first,_1) (example_1);

std::map<int,std::string>::value_type example_2 (std::make_pair (2,"boo"));
int value_2 = boost::bind (&std::pair<int,std::string>::first,_1) (example_2);

第一个示例运行良好,但第二个示例在绑定完成后无法编译。我看过文件stl_map.hvalue_type定义如下:

typedef std::pair<const _Key, _Tp> value_type;

我看不出有什么不同。如果有人能告诉我,以及第二个示例无法编译的原因,我将不胜感激。

编译错误信息为:

.../include/boost/bind/mem_fn.hpp:333:36: error: no matching function for call to ‘get_pointer(const std::pair<const int, std::basic_string<char> >&)’
make: *** [main.o] Error 1

提前致谢!

【问题讨论】:

    标签: c++ boost stl boost-bind


    【解决方案1】:

    不同之处在于在映射值类型中使用了conststd::pair&lt;int,std::string&gt;::first 不是 std::pair&lt;const int,std::string&gt;::first 上的可访问项目。是的,pair 定义了从 const 版本到非常量版本的隐式转换,但是为了调用这样的成员函数,不考虑这种转换。 pair 的这些用法可能看起来很相似,但实际上它们是完全独立的类,就字段位置等可能的去向而言彼此无关。

    本质上,你被要求构建类似的代码

    std::pair<const int,std::string> example(3, "Hello");
    example.std::pair<int,std::string>::first
    

    这是无效的。

    【讨论】:

    • 是的,我没有意识到const...需要更多的咖啡。谢谢!
    【解决方案2】:

    mapvalue_type 有一个 const 密钥(在您的情况下为 const int),而您使用的密钥对没有(在您的情况下为纯 int)。

    【讨论】:

      猜你喜欢
      • 2013-06-04
      • 2011-03-24
      • 1970-01-01
      • 2012-05-20
      • 2014-03-15
      • 2013-05-18
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多