【发布时间】:2012-02-21 19:59:23
【问题描述】:
我正在尝试熟悉 STL 库,但我无法理解我的编译错误。我已经使用编译器错误字符串“无法为...推断模板参数”搜索其他问题,但没有一个答案似乎适用或相关。
错误 4 错误 C2784: 'bool std::operator &,const std::unique_ptr<_ty2> &)' : 无法推断出 'const 的模板参数std::unique_ptr<_ty> &' from 'const std::string' c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional 125
我正在编写一个简单的解释器来计算一个变量中的导数/积分。我想要一张地图,用于将用户的输入与内部控制代码相匹配。 key 是 trig(或其他)函数,int 是控制代码。我使用一个单独的头文件来#define 函数,但对于这个例子,我只是使用整数文字。我正在使用 Visual Studio:
#include <cstdio>
#include <map>
using namespace std;
int main(int argc, char** argv) {
map< string, int > functions;
functions.insert( pair<string, int>("sin", 1) );
return 0;
}
编辑:
在尝试了 Serge 的(有效的)答案之后:
functions.insert(std::make_pair(std::string("sin"), 1));
我意识到了错误并尝试了这个:
pair<string, int> temp = pair<string,int>("cos",2);
functions.insert(temp);
虽然这可能不是最理想的,但它说明了在插入地图之前没有构造对对象的问题。
【问题讨论】:
-
使用
std::map<X,Y>::value_type是std::pair<*const* X, Y>。 -
functions["sin"] = 1;也可以完美运行 :-) -
@MartinKristiansen 这就是我要做的。它稍微贵一些,并且要求该值是默认可构造的。这对整数来说很好,但对于某些类来说可能是禁止的或不可能的。
-
关于你的编辑:你不需要在插入之前定义
temp,这不是错误,你也不需要调用make_pair——虽然它的优点是没有需要明确指定类型——pair-constructor 也可以工作。实际上我会投票给@MartinKristiansen 解决方案,因为它简短易读。