首页 > 解决方案 > 我可以将向下转换应用于迭代器吗?

问题描述

我需要知道我是否通过应用向下转换来向模板类发送正确类型的容器。

// C++ program to demonstrate input iterator
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
    vector<int> v1 = { 1, 2, 3, 4, 5 };

    // Declaring an iterator
    vector<int>::iterator i1;
    bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
    if(bi != nullptr)
      cout << "Succesfull" << endl;
    for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
        // Accessing elements using iterator
        cout << (*i1) << " ";
    }
    return 0;
}

我得到错误:

prog.cpp: In function ‘int main()’:
prog.cpp:12:2: error: ‘bidirectional_iterator’ was not declared in this scope
  bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
  ^
prog.cpp:12:27: error: ‘bi’ was not declared in this scope
  bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
                           ^
prog.cpp:12:45: error: ‘i1’ does not name a type
  bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
                                             ^
prog.cpp:12:47: error: expected ‘&gt;’ before ‘&amp;’ token
  bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
                                               ^
prog.cpp:12:47: error: expected ‘(’ before ‘&amp;’ token
prog.cpp:12:48: error: expected primary-expression before ‘&gt;’ token
  bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
                                                ^
prog.cpp:12:53: error: expected ‘)’ before ‘;’ token
  bidirectional_iterator & bi = dynamic_cast<i1&>(i1);

无论如何我可以检查容器中迭代器的类型,以便我可以控制它是否会在模板类中传递?

标签: c++stliteratorpolymorphismdowncast

解决方案


看起来您完全误解了标准库中的迭代器。首先,如果您发现自己在dynamic_cast使用任何标准库类型(一个值得注意的例外 - he-he, pun - is std::exception,也许还有一些我现在没有想到的其他类型),那么您做错了什么。绝大多数 STL 类型都不是多态的,因此永远不应该这样使用。

迭代器也是如此。您不需要强制std::vector::iterator转换为biderectional_iterator,而只需在需要此类迭代器的地方使用它。有iterator_traits,当与向量迭代器一起使用时,将表明向量的迭代器是双向的iterator_category。查看有关 iterator_traits的更多信息

trait 的美妙之处在于所有这些逻辑都是在编译时完成的,所以如果你试图在迭代器中使用它无法处理的场景,你最终会出现编译错误,并且可以立即修复程序。


推荐阅读