用std :: transform填充std :: map(错误:不能推断出参数)

时间:2011-05-07 13:06:39

标签: c++ visual-c++ stl c++11 visual-c++-2010

我正在尝试使用std :: transform填充std :: map。下一个代码编译没有错误:

std::set<std::wstring> in; // "in" is filled with data
std::map<std::wstring, unsigned> out;

std::transform(in.begin(), in.end()
,   boost::counting_iterator<unsigned>(0)
,   std::inserter(out, out.end())
,   [] (std::wstring _str, unsigned _val) { return std::make_pair(_str, _val); }
);

但如果我替换字符串

,   [] (std::wstring _str, unsigned _val) { return std::make_pair(_str, _val); }

,   std::make_pair<std::wstring, unsigned>

,   std::ptr_fun(std::make_pair<std::wstring, unsigned>)

我收到错误:

foo.cpp(327): error C2784: '_OutTy *std::transform(_InIt1,_InIt1,_InTy (&)[_InSize],_OutTy (&)[_OutSize],_Fn2)' : could not deduce template argument for '_InTy (&)[_InSize]' from 'boost::counting_iterator<Incrementable>'
      with
      [
          Incrementable=unsigned int
      ]
      C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\algorithm(1293) : see declaration of 'std::transform'
foo.cpp(327): error C2784: '_OutTy *std::transform(_InIt1,_InIt1,_InIt2,_OutTy (&)[_OutSize],_Fn2)' : could not deduce template argument for '_OutTy (&)[_OutSize]' from 'std::insert_iterator<_Container>'
      with
      [
          _Container=std::map<std::wstring,unsigned int>
      ]
      C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\algorithm(1279) : see declaration of 'std::transform'
foo.cpp(327): error C2784: '_OutIt std::transform(_InIt1,_InIt1,_InTy (&)[_InSize],_OutIt,_Fn2)' : could not deduce template argument for '_InTy (&)[_InSize]' from 'boost::counting_iterator<Incrementable>'
      with
      [
          Incrementable=unsigned int
      ]
      C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\algorithm(1267) : see declaration of 'std::transform'
foo.cpp(327): error C2914: 'std::transform' : cannot deduce template argument as function argument is ambiguous

依旧...... 请解释编译的问题是什么?

更新:感谢您的回答。我意识到,这是MSVC2010的bug。顺便说一句

&std::make_pair<const std::wstring&, const unsigned&>

导致相同的错误

2 个答案:

答案 0 :(得分:7)

这是Visual C ++库实现中的一个错误。以下程序演示了该问题:

#include <utility>

int main()
{
    &std::make_pair<int, int>;
};

该程序产生错误:

error C2568: 'identifier' : unable to resolve function overload

在C ++语言规范中,make_pair不是重载函数。 Visual C ++ 2010库实现包括四个重载,它们采用左值和右值引用的各种组合。

虽然允许C ++标准库的实现为成员函数添加重载,但是不允许为非成员函数添加重载,因此这是一个错误。

错误was reported and will be fixed in the next version of Visual C++。但是,正如STL在解决该bug时所做的那样,你需要将模板参数设为std::make_pair左值引用:

&std::make_pair<const std::wstring&, const unsigned&>

答案 1 :(得分:3)

g ++ 4.4.5编译它没有错误。似乎是Visual Studio 10 defect