详述trait和policy演化(一)
#define SIZE 5;
int a[SIZE]={10,11,12,13,14};
int Toatal(const int a[], int size)
{
int i=0, total=0;
while(i<size)
{
total+=a[i]
i++;
}
return total;
}
int Total(const int* a0, const int* an)
{
int total=0;
while(a0!=an)
{
total+=*a0;
a0++;
}
return total;
}
template<typename T>
T Total(const T* beg, const T* end)
{
T total=0;
while(beg!=end)
{
total+=*beg;
beg++;
}
return total;
}
int a[5]={0,1,2,3,4};
char b[5]={'a', 'b', 'c', 'd', 'e'};
void main()
{
int sum0=Total(a, a+5);
int sum1=Total(b, b+5);
}
template<typename R, typename T>
R Total(const T* beg, const T* end)
{
R total=R();
while(beg!=end)
{
total+=*beg;
beg++;
}
return total;
}
template<typename T> class TotalTrait;
template<typename T> class TotalTrait{};(
template<>
class TotalTrait<char>
{
public:
typedef int R;
};
template<>
class TotalTrait<int>
{
public:
typedef long R;
};
template<>
class TotalTrait<float>
{
public:
typedef double R;
};
template<typename T>
typename TotalTrait<T>::R Total(const T* beg, const T* end)
{
typedef typename TotalTrait<T>::R R;
R total=R();
while(beg!=end)
{
total+=*beg;
beg++;
}
return total;
}
template<>
class TotalTrait<A>
{
public:
typedef B R;
};
template<>
class TotalTrait<char>
{
public:
typedef int R;
static const R zero=0;
};
template<>
class TotalTrait<int>
{
public:
typedef long R;
static const R zero=0;
};
template<typename T>
typename TotalTrait<T>::R Total(const T* beg, const T* end)
{
typedef typename TotalTrait<T>::R R;
R total=TotalTrait<T>::zero;
while(beg!=end)
{
total+=*beg;
beg++;
}
return total;
}
class TotalTrait<float>
{
public:
typedef double R;
static const R zero=0.0;
};
xxx.hpp:
class TotalTrait<float>
{
public:
typedef double R;
static const R zero;
};
xxx.cpp:
const TotalTrait<float>::R zero=0.0;
template<>
class TotalTrait<char>
{
public:
typedef int R;
static R Zero(){
return 0;
}
};
template<>
class TotalTrait<int>
{
public:
typedef long R;
static R Zero(){
return 0;
}
};
class TotalTrait<float>
{
public:
typedef double R;
static R Zero(){
return 0.0;
}
};
template<typename T>
typename TotalTrait<T>::R Total(const T* beg, const T* end)
{
typedef typename TotalTrait<T>::R R;
R total=TotalTrait<T>::Zero();
while(beg!=end)
{
total+=*beg;
beg++;
}
return total;
}
template<typename T, typename RE>
typename RE::R Total(const T* beg, const T* end)
{
typedef typename RE::R R;
R total=RE::Zero();
while(beg!=end)
{
total+=*beg;
beg++;
}
return total;
}
template<typename T, typename RE=TotalTrait<T> >
class CTotal
{
public:
static typename RE::R Total(const T* beg, const T* end)
{
typedef typename RE::R R;
R total=RE::Zero();
while(beg!=end)
{
total+=*beg;
beg++;
}
return total;
}
};
template<typename T>
typename TotalTrait<T>::R Total(const T* beg, const T* end)
{
return CTotal<T>::Total(beg, end);
}
template<typename T, typename RE>
typename TotalTrait<T>::R Total(const T* beg, const T* end)
{
return CTotal<T, RE>::Total(beg, end);
}
本文出自 “狼窝” 博客,转载请与作者联系!