不确定您所说的“开销”是什么意思。如果它简化了您编写代码的方式,请使用它,否则请坚持使用速记。
如果它仅在受限范围内使用,请将 typedef 放在同一范围内。然后它就不需要发布、记录或出现在任何 UML 图上。例如(我并不认为这是在其他方面最好的代码):
int totalSize() {
typedef std::map<Key, Value> DeDuplicator;
DeDuplicator everything;
// Run around the universe finding everything. If we encounter a key
// more than once it's only added once.
// now compute the total
int total = 0;
for(DeDuplicator::iterator i = everything.begin(); i <= everything.end(); ++i) {
total += i->second.size(); // yeah, yeah, overflow. Whatever.
}
return total;
}
结合 Ferruccio 的建议(如果您正在使用 boost),循环变为:
BOOST_FOREACH(DeDuplicator::pair p, everything) {
total += p.second.size();
}
并结合 bk1e 的建议(如果您使用 C++0x 或具有其中的功能),并假设 BOOST_FOREACH 以我认为应该基于它通常可以处理兼容类型的隐式转换的方式与 auto 交互:
std::map<Key, Value> everything;
// snipped code to run around...
int total = 0;
BOOST_FOREACH(auto p, everything) {
total += p.second.size();
}
不错。