大家好,又见面了,我是全栈君
扮演“特性萃取机”角色,萃取各个迭代器的特性(迭代器的相应类型)
模板特例化:提供一份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;
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/120234.html原文链接:https://javaforall.cn