问题:模板来获得地图元素默认值
我试图做一个函数getmap
是得到一个map<string, string>
元素,但如果不存在返回指定的默认值(即getmap(mymap, "keyA", mydefault);
我模板它int, float
和char*
返回类型,但我得到一个错误:虽然我没有使用
error C2664: 'getmap' : cannot convert parameter 3 from 'const char *' to 'char *const '
char *const
。这是为什么发生?
的代码:
template <typename T> inline
T getmap(const std::map<std::string, std::string> &m, const char* key, const T def, T (*f)(const char*) = NULL) {
std::map<std::string, std::string>::const_iterator i = m.find(std::string(key));
return i == m.end() ? def : (f == NULL ? i->second.c_str() : f(i->second.c_str()));
}
inline int getmap(const std::map<std::string, std::string> &m, const char* key, const int def) {
return getmap<int>(m, key, def, &std::atoi);
}
float atofl(const char* s) {
return (float)std::atof(s);
}
inline float getmap(const std::map<std::string, std::string> &m, const char* key, const float def) {
return getmap<float>(m, key, def, &atofl);
}
inline char* getmap(const std::map<std::string, std::string> &m, const char* key, const char* def) {
return getmap<char*>(m, key, def); // ERROR HERE
}
为什么你想在一个const char *传递给需要一个指向函数的功能? – dchhetri
为什么你使用'char *'? –
@ user814628 - 你指的是哪里?谢谢 – mchen