boost :: transform_iterator不适用于std :: bind(&Pair :: first,_1)吗?

Art*_*syn 5 c++ boost c++11

迭代槽键集的传统任务std::map使我陷入另一场混乱,这里似乎还没有讨论过。

简而言之,此代码无法编译(大量使用C ++ 11):

typedef std::pair<int, int> Pair;
vector<Pair> v {Pair(1,2), Pair(2,3)};
using namespace std::placeholders;
auto choose_first = std::bind(&Pair::first, _1);
boost::make_transform_iterator(v.begin(), choose_first);
Run Code Online (Sandbox Code Playgroud)

错误信息如下。

no type named 'result_type' in 'struct std::_Bind<std::_Mem_fn<int std::pair<int, int>::*>(std::_Placeholder<1>)>' 
Run Code Online (Sandbox Code Playgroud)

同时,更改std::bindboost::bind可解决问题。但是我的项目中有一个std::bind仅使用的代码约定。

有什么建议怎么办?(我应该向Boost团队写错误报告吗?)

Xeo*_*Xeo 4

有更好的方法来迭代 a std::map(或任何其value_type为 的容器pair<T,U>)的键,即Boost.Rangemap_keys适配器(还有一个map_values):

#include <boost/range/adaptor/map.hpp>
#include <utility>
#include <vector>
#include <iostream>

int main(){
  typedef std::pair<int, int> Pair;
  std::vector<Pair> v {Pair(1,2), Pair(2,3)};
  for(auto& first : v | boost::adaptors::map_keys){
    std::cout << first << " ";
  }
}
Run Code Online (Sandbox Code Playgroud)

但回到你的问题:所有 Boost 库都使用Boost.Utility 函数result_of,无论出于何种原因,它都不会回退到,并且如果它在没有你告诉它的情况下可用,std::result_of也不会使用。decltype您可以通过将其放在#define BOOST_RESULT_OF_USE_DECLTYPE第一个 Boost include 之前来实现此目的。

然而,这仍然无法使您的代码使用 Clang 3.1 SVN + libc++ 进行编译。这是我使用的代码:

#define BOOST_RESULT_OF_USE_DECLTYPE
#include <boost/iterator/transform_iterator.hpp>
#include <utility>
#include <vector>
#include <functional>

int main(){
  typedef std::pair<int, int> Pair;
  std::vector<Pair> v {Pair(1,2), Pair(2,3)};
  using namespace std::placeholders;
  auto choose_first = std::bind(&Pair::first, _1);
  boost::make_transform_iterator(v.begin(), choose_first);
}
Run Code Online (Sandbox Code Playgroud)

编译为:

clang++ -std=c++0x -stdlib=libc++ -Wall -pedantic -Ipath/to/boost -Wno-mismatched-tags t.cpp
Run Code Online (Sandbox Code Playgroud)

GCC 4.7 似乎可以很好地接受这一点,所以我猜这是 libc++ 中的一个错误。