[英]C++ Iterator declare from typedef std::map as template argument
How can I declare an iterator for template argument map? 如何声明模板参数映射的迭代器?
I know I could pass it as argument from main function as another template argument, but if I don't, how can I declare it? 我知道我可以将其作为其他模板参数从主函数传递为参数,但是如果不这样做,如何声明它?
template< typename container >
int print_data( container map )
{
map::iterator iter; // this is wrong
return 0;
}
int main()
{
typedef std::map< int, double > Map;
Map new_map;
print_data< Map >( new_map );
}
While 而
map::iterator iter; // this is wrong
is true. 是真的。 That's only because you use the scope resolution operator on an object, instead of something that designates a scope, like a class name or a namespace.
这仅是因为您在对象上使用范围解析运算符,而不是在诸如类名或名称空间之类的用于指定范围的对象上使用。 So this:
所以这:
typename container::iterator iter;
Would be correct. 是正确的。 Note the
typename
keyword is important and mandatory. 请注意,
typename
关键字是重要且必填的。 You must let the compiler know this dependent name you are accessing is a type, so the line would be parsed as a declaration. 您必须让编译器知道您正在访问的此从属名称是一种类型,因此该行将被解析为声明。
If you are able to use a C++11 (or later) compiler, you have couple of more ways to declare iter
. 如果您能够使用C ++ 11(或更高版本)编译器,则可以使用多种其他方式声明
iter
。
If you can declare and initialize it in one statement, you can use: 如果可以在一个语句中声明并初始化它,则可以使用:
auto iter = map.begin();
You can also use decltype
to deduce the type. 您也可以使用
decltype
推断类型。
using iterator_type = decltype(map.begin()); iterator_type iter;
I would recommend using the first method. 我建议使用第一种方法。 It is less code to deal with.
处理的代码更少。 It's also a better programming habit to declare and initialize a variable in one statement.
在一个语句中声明和初始化变量也是一种更好的编程习惯。
typename Container::iterator iter = ...;
编译器默认将模板成员视为变量,如果它是一种类型,则必须使用“ typename”表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.