迭代器与traits编程技法

本文探讨了迭代器在设计模式中的重要性,特别是在STL中的应用,以及如何使用迭代器作为不同数据容器和算法之间的桥梁。迭代器类似于智能指针,主要通过重载`operator*`和`operator->`来实现其功能。文章还提到了Traits编程技法,当需要获取迭代器关联类型如value type时,利用模板参数推导的局限性,并指出在某些情况下需要专门的Traits类来获取这些信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2013-06-15 wcdj


迭代器设计思维

(1) 迭代器(iterators)是一种抽象的设计概念,现实程序语言中并没有直接对应于这个概念的实物。

(2)《设计模式》一书提供有23个design patterns的完整描述,其中iterator模式定义为:提供一种方法,使之能够依序巡防某个聚合物(容器)所含的各个元素,而又无需暴露该聚合物的内部表述方式。

(3) 不论是泛型思维或STL的实际运用,iterators都扮演着重要的角色。STL的中心思想在于:将数据容器(containers)和算法(algorithms)分开,彼此独立设计,最后再以一贴胶着剂将它们撮合在一起。容器和算法的泛型化,从技术角度看并不困难,C++的class templates和functiontemplates可分别达成目标。如何设计出两者之间的良好胶着剂才是大难题。以算法find为例,以下是容器、算法、迭代器的合作展示:

/**
   *  @if maint
   *  This is an overload used by find() for the Input Iterator case.
   *  @endif
  */
  template<typename _InputIterator, typename _Tp>
    inline _InputIterator
    __find(_InputIterator __first, _InputIterator __last,
	   const _Tp& __val, input_iterator_tag)
    {
      while (__first != __last && !(*__first == __val))
	++__first;
      return __first;
    }

只要给予不同的迭代器,find便能够对不同的容器进行查找操作:

// file: 3find.cpp
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
	const int arraySize = 7;
	int ia[arraySize] = {0,1,2,3,4,5,6};

	vector<int> ivect(ia, ia+arraySize);
	list<int> ilist(ia, ia+arraySize);
	deque<int> ideque(ia, ia+arraySize);

	vector<int>::iterator it1 = find(ivect.begin(), ivect.end(), 4);
	if (it1 == ivect.end())
	{
		cout << "4 not found." << endl;
	}
	else
	{
		cout << "4 found. " << *it1 << endl;  
	}

	list<int>::iterator it2 = find(ilist.begin(), ilist.end(), 6);
	if (it2 == ilist.end())
	{
		cout << "4 not found." << endl;
	}
	else
	{
		cout << "4 found. " << *it2 << endl;  
	}

	deque<int>::iterator it3 = find(ideque.begin(), ideque.end(), 8);
	if (it3 == ideque.end())
	{
		cout << "4 not found." << endl;
	}
	else
	{
		cout << "4 found. " << *it3 << endl;  
	}

	return 0;
}

/*
output:
mba:stl gerryyang$ g++ -o 3find 3find.cpp 
mba:stl gerryyang$ ls
3find		3find.cpp
mba:stl gerryyang$ ./3find 
4 found. 4
4 found. 6
4 not found.
*/

(4) 迭代器是一种smart pointer。迭代器是一种行为类似指针的对象,而指针的最常见行为是dereference和member acess,因此迭代器最重要的工作就是对operator*和operater->进行overloading工作。在C++标准库中auto_ptr是一个用来包装native pointer的对象,以解决声名狼藉的memory leak问题,auto_ptr用法和原生指针一模一样:

#include <iostream>
#include <string>
#include <memory>// auto_ptr class

using std::cout;
using std::endl;
using std::string;
using std::auto_ptr;

void f1()
{
	int *ip = new int(123);// dynamically allocate a new object
	cout << "&ip = " << ip << "; *ip = " << *ip << endl;

	/* code that throws an exception that is not caught inside f1() */

	delete ip;
}

void f2()
{
	auto_ptr<int> ap(new int(456));// allocate a new object
	cout << "&ap = " << &ap << "; *ap = " << *ap << endl;

	/* code that throws an exception that is not caught inside f2() */

	// auto_ptr freed automatically when function ends
}

void f3()
{
	auto_ptr<string> ap_string(new string("delphiwcdj"));
	cout << "ap_string = " << *ap_string << endl;

	*ap_string = "gerry";
	cout << "ap_string = " << *ap_string << endl;

	if (ap_string->empty())
	{
		cout << "ap_string is empty" << endl;
	}
	else
	{
		cout << "ap_string is non-empty" << endl;
	}

}


int main() 
{
	cout << "auto_ptr usage\n" << endl;

	f1();

	f2();

	f3();

	return 0;
}
/*
g++ -Wall -g -o auto_ptr auto_ptr.cpp 

output:
auto_ptr usage

&ip = 0x804b008; *ip = 123
&ap = 0xbfa85d70; *ap = 456
ap_string = delphiwcdj
ap_string = gerry
ap_string is non-empty
*/

(5) 为了完成一个针对某种容器而设计的迭代器,我们无可避免地会暴露了太多此容器实现细节,即要设计出某种容器的迭代器,首先必须对此容器的实现细节有非常丰富的了解,既然这无可避免,干脆就把迭代器的开发工作交给容器的设计者好了,如此一来,所有实现细节反而得以封装起来不被使用者看到。这正是为什么每一种STL容器都提供有专属迭代器的缘故。

(6) 迭代器相应型别(associated types)

假设算法中有必要声明一个变量,以“迭代器所指对象的型别”为型别如何是好?毕竟C++只支持sizeof(),并未支持typeof(),即便动用RTTI性质中的typeid(),获得的也只是型别名称,不能拿来做变量声明之用。解决办法是:利用function template的参数推导(argument deducation)机制。

PS: 面向对象编程所依赖的多态性称为运行时多态性,泛型编程所依赖的多态性称为编译时多态性参数式多态性

#include <iostream>
using namespace std;

template <class I, class T>
void func_impl(I iter, T t)
{
    T tmp;// 这里解决了问题,T就是迭代器所指之物的型别,本例为int/short

    // 这里做原本func()应该做的全部工作
    cout << "func_impl: sizeof(tmp)=" << sizeof(tmp) << endl;
    cout << "func_impl: t=" << t << endl;
}

template <class I>
inline
void func(I iter)
{
    func_impl(iter, *iter);// func的全部工作移交给func_impl
}

int main()
{
    int i = 10;
    func(&i);

    short j = 20;
    func(&j);

    return 0;
}
/*
output:
mba:stl gerryyang$ g++ -o 3find 3find.cpp 
mba:stl gerryyang$ ./3find 
func_impl: sizeof(tmp)=4
func_impl: t=10
func_impl: sizeof(tmp)=2
func_impl: t=20
*/


#include <iostream>
using namespace std;

template <typename I, typename T>
T func_impl(I iter, T t)
{
	T tmp;// 这里解决了问题,T就是迭代器所指之物的型别,本例为int/short

	// 这里做原本func()应该做的全部工作
	cout << "func_impl: sizeof(tmp)=" << sizeof(tmp) << endl;
	cout << "func_impl: t=" << t << endl;
	return t+1;
}

template <typename I>
inline
void func(I iter)
{
	*iter = func_impl(iter, *iter);// func的全部工作移交给func_impl
}

int main()
{
	int i = 10;
	func(&i);
	cout << "i=" << i << endl;

	short j = 20;
	func(&j);
	cout << "j=" << j << endl;

	return 0;
}
/*
output:
mba:stl gerryyang$ g++ -o 3find 3find.cpp 
mba:stl gerryyang$ ./3find 
func_impl: sizeof(tmp)=4
func_impl: t=10
i=11
func_impl: sizeof(tmp)=2
func_impl: t=20
j=21
*/


注意:迭代器相应型别不只是“迭代器所指对象的型别(value type)”一种而已,最常用的相应型别有5种,然而并非任何情况下任何一种都可以利用上述的template参数推导机制来取得。


Traits编程技法

利用function template的参数推导技巧并非全面可用,例如,value type必须用于函数的返回值就素手无策了,毕竟函数的“template参数推导机制”推而导之的只是参数,无法推导函数的返回值型别。



参考:

[1] STL源码剖析,第三章


C++ traits 是一种强大的编程技术,用于获取编译时类型信息或执行特定于类型的计算。它们提供了一种静态类型检查的方法,常用于模板编程、元编程以及类型安全的设计模式中。Traits 主要用于以下目的: 1. **类型检测**:traits 可以帮助你在编译时确定某个类型是否支持某种操作,比如是否有特定成员函数、是否为标准库中的特定类型等。 2. **参数化选择**:根据类型的不同动态选择行为,例如选择不同算法的实现,或者为不同类型的容器提供适配器。 3. **类型转换**:traits 有时用来提供类型转换的工具,如 `std::enable_if`,确保只有当条件满足时才启用某些代码。 4. **类型增强**:增加对类型特性的描述,比如获取类型大小、指针类型、引用类型等。 `std::integral_constant` 和 `std::is_*`(如 `std::is_arithmetic`, `std::is_same`)是 C++11 引入的一些基本 traits 类型。更复杂的 traits 可能涉及到自定义模板类,比如 Boost 框架中的 `boost::mpl` 或现代 C++ 标准库中的 `<type_traits>`。 使用 traits 的一个常见示例是模板元编程,例如计算两个类型之间的最大公因子: ```cpp template <typename T, typename U> struct gcd_t { static_assert(std::is_integral<T>::value && std::is_integral<U>::value, "gcd only works on integral types"); // 使用 traits 获取类型信息并进行计算 // ... }; // 实例化 gcd 对整数类型 template <int A, int B> using gcd = gcd_t<int, int>; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值