使用typedef,简化代码调整

ZDNet软件频道 时间:2002-11-26 作者:BUILDER.COM |  我要评论()
本文关键词:
我们强烈要求高级程序员经常使用typedef,因为它可以增强代码透明性并帮助你编写与平台无关的代码。Typedef常常可以帮助你减少书写量,特别当你使用标准模板库(STL)时。

我们强烈要求高级程序员经常使用typedef,因为它可以增强代码透明性并帮助你编写与平台无关的代码。Typedef常常可以帮助你减少书写量,特别当你使用标准模板库(STL)时。下面是一个例子:

typedef std::vector< std::string> StringsArray;
StringsArray aEmployeeNames;
// [...实现它的代码]

StringsArray::const_iterator
itFirst = aEmployeeNames.begin(),
itLast = aEmployeeNames.end();
while ( itFirst != itLast)
{
std::cout << "Name: " << *itFirst << std::endl;
++ itFirst;
} 

使用typedef的另一个好处就是它允许你做代码调整(tuning)(即优化代码),尤其是当你使用STL时。

STL允许你高层编程——用概念。如果一系列约束可以施加到某个类型中,那么该类型就是概念的模型。

举例来说,让我们看看容器(Container)的概念。Std::vector、std::list、和std::deque都是容器,它们共享一个界面:容器界面。

template >
class Cont {
public:
// these are typedefs - so they can be seen as part of the interface also
typedef [...] allocator_type;
typedef [...] size_type;
typedef [...] difference_type;
typedef [...] reference;
typedef [...] const_reference;
typedef [...] value_type;
typedef [...] iterator;
typedef [...] const_iterator;
typedef [...] reverse_iterator;
typedef [...] const_reverse_iterator;

iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
size_type size() const;
size_type max_size() const;
bool empty() const;
A get_allocator() const;
iterator erase(iterator it);
iterator erase(iterator first, iterator last);
void clear();
void swap(Cont x);
}; 

百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134