请教一个trait技术的用法
假如我需要设计一个作用在点上面的范型函数,为了优化此函数需要知道点坐标用的数值的类型。为此我约定用户的点类型value_trait的value_type就是点的坐标类型。
这样我的函数就可以写成:
template<class point>
void foo(point &pt)
{
typedef value_trait<point>::value_type value_type;
//这里的value_type就是point的坐标类型
…………
}
如果用户的某个类型例如CPoint需要调用我得foo函数,那么他需要特例化一下CPoint的value_trait。也就是说用户需要写下:
struct value_trait<CPoint>{
typedef long value_type;
}
现在我设计了一个点的模板类
template<class value_type>
struct point{
value_type x,y;
};
为了让我得point模板类拥有value_trait我该如何写代码?
最笨的一个方法是:
先定义宏:
#define point_value_trait(type) struct value_trait<point<type> >{\
typedef type value_type; }
然后写下:
point_value_trait(int)
point_value_trait(float)
point_value_trait(double)
point_value_trait(short)
…………
但这种方法太让人伤感了。另外的稍微好一点方法是:
先写下
template<class type>
struct value_trait{
typedef typename type::value_type value_type;
}
然后改写我得point模板
template<class type>
struct point{
typedef type value_type;
type x,y;
};
这样一定程度的解决了问题,但是假如另外有仁兄有自己的point的模板类
template<class type>
struct point1{
type x,y;
};
而此point1没有定义value_type,那么用此模板的类型将很难调用我得foo函数。
请问,如果我完全没有写value_trait的缺省实现和没有在point中加入
typedef type value_type这行代码,如何实现我得point模板的value_trait。