c++ - 从迭代器转换为变量的类型。 (C++11 模板)

标签 c++ c++11 templates iterator

我有一个模板类,其中有一个 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 validateStrvector<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/

相关文章:

c++ - constexpr 函数不需要返回常量表达式吗?

c++ - C++11 的编译器标志 - 找不到计时文件

c++ - 删除 std::multiset 中的元素导致不相关的迭代器无效

c++ - 'round' 不是 'std' 的成员

c++ - 我可以将 "using namespace std"放入我的 namespace 中吗?

c++ - 如何使用 boost lexical_cast 库来检查输入

c# - UWP 中的模板化控件与自定义控件。网上没有找到明确的答案

c++ - 将具有外部实现的模板编译为静态库

c++ - 减少彼此紧密关联的模板参数

c++ - 在 .h 文件中包含仅用于私有(private)数据的 header