我有一个函数需要能够接受不同的类型,然后将它们存储在单独的映射中。 (因此,如果它接收到一个整数,它应该进入整数映射等)。
我当前的代码:
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/