c++ - 获取具有默认值的 map 元素的模板

标签 c++ dictionary

问题:

我正在尝试创建一个函数 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
}

最佳答案

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

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

然后你试图传递一个 const char*char* const ,正如错误所说。您可以将非常量传递给常量,但反之则不行。

所以改为这样写......

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

关于c++ - 获取具有默认值的 map 元素的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16569110/

相关文章:

c++ - 在共享指针的值中调用 std::swap 会调用一堆构造函数和析构函数

c++ - 使用 GDB 和 C++ 调试内存错误

java - 如果 ArrayList<String> 是 Map 中的键,如何从 ArrayList<String> 中检索值?

python - 将 dictreader 转换为字典字典的优雅方法

C++: map 的迭代

c++ - "class :"在 C++ 中是什么意思?

c++ - 将 lambda 与自动声明结合使用还是就地使用?

ios - 从 Application Support Directory 中的 plist 中读取翻译

c++ - Visual Studio 不为 KinectBridgeWithOpenCVBasics D2D C++ 示例使用额外的包含目录,但为其他解决方案使用。

python - 如何在python中基于dct.keys创建组