我有一个模板类,其中有一个 vector 和默认值
T _default;
vector<T> Vals;
我想遍历它并根据默认类型(字符串/整数/ double )打印值。
所以我写了
if (typeid(int) == typeid(_default))
{
for each(auto itr in Vals)
{
//logic to process each element in vector
int temp;
//temp = *itr; <------ how to convert from iterator to the value (value held in vector)
}
}
else if (typeid(string) == typeid(_default))
{
for each(auto itr in Vals)
{ //logic to process each element in vector
string temp;
//temp = *itr; <------ how to convert from iterator to the value (value held in vector)
}
}
else if (typeid(double) == typeid(_default))
{
for each(auto itr in Vals)
{
//logic to process each element in vector
double temp;
//temp = *itr; <------ how to convert from iterator to the value (value held in vector)
}
}
如何将迭代器转换为对应的int/string/double。当我使用 *itr
取消引用它时给我error C2100: illegal indirection
错误。
更新:
抱歉更新 - 但我实际上想比较字符串的值说 string validateStr
到 vector<T> Vals
中包含的值.所以我需要知道 Vals
中存储的值的类型然后通过对 Vals
中的每个值执行 (string to int)/(string to double)/(string(as is)) 来比较字符串.所以基本上这段代码将检查 _default
是否值实际上是允许的 Vals
中存在的任何值.
最佳答案
在范围循环中,“迭代变量”具有元素的类型。
它不是迭代器。
您不能像这样编写函数,因为无论 T
是什么,整个函数都必须是类型正确的。
您可以做的是使用重载(或模板化)函数并将值传递给它:
void print(int i) { cout << "int " << i; }
void print(string s) { cout << "string " << s; }
// ...
for (auto v: Vals)
{
print(v);
}
关于c++ - 从迭代器转换为变量的类型。 (C++11 模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575994/