扮演“特性萃取机”角色,萃取各个迭代器的特性(迭代器的相应类型)

模板特例化:提供一份template定义式,而其本身仍为templatization

通过class template partial specialization的作用,不论是原生指针或class-type iterators,都可以让外界方便地取其相应类别

原生指针不是class type,如果不是class type就无法为它定义内嵌型别。但模板特例化解决了该问题

  template<class T>

  class C{...};    // 这个泛化版本允许(接受)T为任何型别

  template<class T>

  class C<T*>{...}; // 这个特化版本仅适用于“T为原生指针”的情况

  

#pragma once

template <class T>
class MyIter
{
public:
	MyIter(T *p = 0):ptr(p){}
	MyIter(MyIter<T> &ths):ptr(ths.ptr){}
	T& operator*(){return *ptr;}

	typedef T value_type;

private:
	T *ptr;	
};


// Partial Specialization 偏特化
template <class T>
struct iterator_traitse
{
	typedef typename T::value_type value_type;
};

template <class T>
struct iterator_traitse<T *>
{
	typedef T value_type;
};

template <class T>
typename iterator_traitse<T *> :: value_type fun(T ite)
{
	return ite;
}

int main()
{
	MyIter<int> ite(new int(8));
	
	// cannot convert from 'MyIter<T>' to 'int'
	int n = fun(ite);

     MyIter<int> p = fun(ite);
return 0; }

 

相关文章:

  • 2022-12-23
  • 2022-03-03
  • 2022-03-06
  • 2021-05-30
  • 2022-12-23
  • 2022-12-23
  • 2021-11-15
  • 2022-12-23
猜你喜欢
  • 2022-01-10
  • 2022-12-23
  • 2021-10-24
  • 2022-12-23
  • 2021-09-21
相关资源
相似解决方案