2013-05-15 21 views
0

问题:模板来获得地图元素默认值

我试图做一个函数getmap是得到一个map<string, string>元素,但如果不存在返回指定的默认值(即getmap(mymap, "keyA", mydefault);

我模板它int, floatchar*返回类型,但我得到一个错误:虽然我没有使用

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 
} 
+1

为什么你想在一个const char *传递给需要一个指向函数的功能? – dchhetri

+0

为什么你使用'char *'? –

+0

@ user814628 - 你指的是哪里?谢谢 – mchen

回答

3

getmap<char*>(m, key, def);

使得getmap一个char*T。您接受的第三个参数是const T。我知道这看起来应该使它成为const char*,但实际上它使它成为char* const

然后,您正在尝试将const char*传递给char* const,如错误所述。你可以传递一个非const到一个const,但不是相反。

所以写这篇文章,而不是...

getmap<const char*>(m, key, def); 
     ^^^^^ 
+0

只要使'const char * const'类型的参数和T? – dchhetri

+0

它再次发生错误:[Live Code](http://ideone.com/JNyhVM)。 – deepmax