I need to know if I am sending a template class the right type of containers by applying downcast.
// 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;
}
I get the error:
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 ‘>’ before ‘&’ token
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
^
prog.cpp:12:47: error: expected ‘(’ before ‘&’ token
prog.cpp:12:48: error: expected primary-expression before ‘>’ token
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
^
prog.cpp:12:53: error: expected ‘)’ before ‘;’ token
bidirectional_iterator & bi = dynamic_cast<i1&>(i1);
Is there anyway I can check the type of iterator in a container so I can control whether it will be passed in a templated class?
Looks like you have completely misunderstood iterators in standard library. First and foremost, if you ever find yourself doing dynamic_cast
with any standard library type (a notable exception - he-he, pun - is std::exception
, and perhaps a couple of other types I am not thinking of right now) you are doing something wrong. The vast majority of STL types are not polymorphic and should never be used as such.
This is true of iterators as well. You do not need to cast std::vector::iterator
to biderectional_iterator
, instead you just use it where such iterator is required. There are iterator_traits
, which, when used with vector iterators will indicate that vector's iterators are bidrectional through iterator_category
. See more information on iterator_traits
The beauty of traits is that all this logic is done at compile time, so if you are trying to use in iterator in a scenario it is no capable to handle, you end up with compile error, and can fix the program immediately.