【发布时间】:2021-04-16 18:59:49
【问题描述】:
我需要知道我是否通过应用向下转换来向模板类发送正确类型的容器。
// 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 ‘>’ 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);
我是否可以检查容器中迭代器的类型,以便控制它是否会在模板类中传递?
【问题讨论】:
-
看起来你正在使用变量作为类型
dynamic_cast<i1&>进行转换 -
您不应将迭代器与
nullptr进行比较。它没有意义,通常它甚至不会编译。此外,dynamic_cast<T&>将在失败时抛出std::bad_cast。如果您正在投射指针,您应该只使用nullptr比较来检查dynamic_cast是否成功。dynamic_cast<T*>在失败时返回nullptr而不是抛出。 -
您可以像使用双向迭代器一样使用迭代器,否则模板实例化将失败。如果它像鸭子一样走路,像鸭子一样嘎嘎叫,那就是鸭子
-
@NathanOliver 是的。这绝对是我需要的。感谢您的建议。
标签: c++ stl iterator polymorphism downcast