BOOST_FOREACH&安培;没有模板的typedef [英] BOOST_FOREACH & templates without typedef
问题描述
当我与BOOST_FOREACH工作,不存在用简单的模板作为载体的问题。但是,当我试图通过地图迭代>比如我需要的typedef元素类型。
When I work with BOOST_FOREACH, there isn't a problem with simple templates as vector. But when I try to iterate through map > for example I need to typedef the element type.
有没有什么解决方法吗?
Is there any workaround?
推荐答案
有一个问题,因为它是一个宏,因此无法处理包含逗号(preprocessor不知道模板)类型。
There is a problem because it is a macro, and therefore cannot handle types containing commas (preprocessor doesn't know about templates).
您还可以在循环之前声明变量,请参阅documentation.
You can also declare the variable before the loop, see documentation.
std::map<int, double> my_map;
//1)
typedef std::pair<int, double> MyPair;
BOOST_FOREACH(MyPair p, my_map) { ... }
//2)
std::pair<int, double> p;
BOOST_FOREACH(p, my_map) { ... }
编辑:
有一个进一步复杂化与的std ::地图
特别是: VALUE_TYPE
不是的std ::对&LT;关键字,值&GT;
,但的std ::对&LT;常量键,值方式&gt;
There is a further complication with std::map
in particular: the value_type
is not std::pair<Key, Value>
, but std::pair<const Key, Value>
.
因此,如果您使用的typedef,一个更合适的方式去(而且唯一方式,如果你想使用的参考的在foreach循环)是使用
Hence, if you go with the typedef, a more proper way (and the only way if you want to use a reference in the foreach loop) is to use
typedef std::pair<const int, double> MyPair;
//or
typedef std::map<int, double>::value_type MyPair;
BOOST_FOREACH(MyPair& ref, my_map) { ... }
不过,如果你想使用循环之前声明的变量是行不通的,因为你不能分配到的std ::对&LT; const int的,双&GT;
实例后(不能分配到常量场),在这种情况下,你只能使用对&LT; INT,双方式&gt;
作为升压手册显示
However, that won't work if you want to use a variable declared before the loop, since you can't assign to a std::pair<const int, double>
instance later (can't assign to the const field), in which case you can only use pair<int, double>
as boost's manual shows.
这篇关于BOOST_FOREACH&安培;没有模板的typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!