C++ 模板到 int

标签 c++ templates

我有一个函数需要能够接受不同的类型,然后将它们存储在单独的映射中。 (因此,如果它接收到一个整数,它应该进入整数映射等)。

我当前的代码:

template<typename T>
void set(const char* _key, T _value) {
    DateTime* dt = new DateTime();

    if(std::is_same<T, int>::value) {
        settingsInt.insert(std::pair<const char*, int>(_key, _value));
        printf("[%s][MESSAGE] Added integer setting (%s, %i)\n", dt->getDateTimeStamp(), _key, _value);
    } else if(std::is_same<T, const char*>::value) {
        printf("[%s][MESSAGE] Added string setting (%s, %s)\n", dt->getDateTimeStamp(), _key, _value);
    } else if(std::is_same<T, double>::value) {
        printf("[%s][MESSAGE] Added double setting (%s, %f)\n", dt->getDateTimeStamp(), _key, _value);
    } else {
        printf("[%s][WARNING] Trying to set setting of unknown type! (%s)\n", dt->getDateTimeStamp(), _key);
    }
}

printf 函数正确显示,if 语句正确地看到传递的是哪种类型。但是,当我尝试将值插入我的 map 时,出现以下错误:

error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]

我的方法能实现我想要的吗?有没有办法轻松地将模板值转换回其整数值?

最佳答案

你基本上说:

if (type of x is int)
   insert x to the int map
if (type of x is char*)
  insert x to the char* map

但这行不通。编译器想要检查插入语句的类型是否正确。两个插入语句

insert x to the int map
insert x to the char* map

不能同时类型正确。保护每个陈述的条件是真还是假是无关紧要的。一条语句可能永远不会被执行,但无论如何它都必须是类型正确的。

正确的方法是为每个允许的类型重载set 函数。无需编写模板。也不需要处理默认情况,对 set 的错误调用根本不会编译。

关于C++ 模板到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33033478/

相关文章:

C++::#include:ing 多个源文件中的模板类头文件?

c++ - 非类型模板数组?

c++ - initializer_list 和模板类型推导

c++ - 从 vector 中获取超出范围的元素

c++ - HEX 字符串转 UTF-8(UNICODE) 字符串

c++ - 具有可变参数模板的递归继承和继承参数问题

javascript - Angular 1.5 通过使用另一个组件返回函数中的 html 结果

c++ - 我可以避免超过 3 个级别的缩进吗?

c++ - 在我的 Qt 程序 (C++) 中添加 QtWebKit 时出错?

c++ - 模板参数列表中的第一个参数如何跳过表单调用参数?