我已经重载了我的函数contains
三遍
// returns true if char c is contained in unordered map um
bool contains(std::unordered_map<char, op>& um, char c){
return um.find(c) != um.end();
}
// returns true if string s is contained in unordered map um
bool contains(std::unordered_map<char, op>& um, std::string& s){
return s.length() == 1 && contains(um, s[0]);
}
// returns true if string s is contained in unordered map um
bool contains(std::unordered_map<std::string, func>& um, std::string& s){
return um.find(s) != um.end();
}
每个重载函数的参数都不同。然而,从这一行(contains(opmap, q_front))
我得到了错误:more than one instance of overloaded function "contains" matches the argument list
.
作为参考,opmap
是 类型std::unordered_map<char, op>
,并且q_front
是string
。op
在这种情况下只是我创建的结构 - 如果需要我可以发布,但我觉得在这种情况下这是不必要的。
我的问题是为什么我会收到这个错误,因为上面的函数调用应该唯一地调用第二个方法头:bool contains(std::unordered_map<char, op>& um, std::string& s){
因为类型opmap
匹配第一个参数,类型q_front
是string
。
更新:
完整的错误信息:
more than one instance of overloaded function "contains" matches the argument list: -- function "contains(std::unordered_map<char, op, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, op>>> &um, std::string s)" (declared at line 48 of "/Users/raleighclemens/Documents/Calc_cpp/calc.h") -- function "contains(std::unordered_map<char, op, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, op>>> &um, std::string &s)" (declared at line 49) -- argument types are: (std::unordered_map<char, op, std::hash<char>, std::equal_to<char>, std::allocator<std::pair<const char, op>>>, std::string)C/C++(308)
雷:
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#define LEFT 0
#define RIGHT 1
#define UNARY 0
#define BINARY 1
struct op{
char symbol;
uint8_t precedence;
uint8_t assoc;
uint8_t type;
std::function<double (double, double)> ashley;
};
struct func{
std::string symbol;
uint8_t type;
std::function<double (double, double)> ashley;
};
bool contains(std::unordered_map<char, op>& um, char c){
return um.find(c) != um.end();
}
// returns true if string s is contained in unordered map um
bool contains(std::unordered_map<char, op>& um, std::string& s){
return s.length() == 1 && contains(um, s[0]);
}
// returns true if string s is contained in unordered map um
bool contains(std::unordered_map<std::string, func>& um, std::string& s){
return um.find(s) != um.end();
}
int main(int argc, char** argv){
std::unordered_map<char, op> opmap;
op op1{'+', 2, LEFT, BINARY, [=] (double a, double b){return a + b;}};
opmap.emplace('+', op1);
std::cout << contains(opmap, "+");
您希望哪个重载将您的呼叫与下面的行相匹配?
std::cout << contains(opmap, "+");
由于您的第二个参数,即"+"
. 它的类型是const char[2]
并且不能匹配到char
。
重载 2 和 3 无法匹配,因为 的类型"+"
具有 const 限定符,但在这两个重载中,您string
作为非常量引用传递。
因此,要解决您的问题,您应该:
"+"
为'+'
使用第一个重载。std::string &
为const std::string &
使用重载 2。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句