2011-02-27 53 views
2

每当有人可能使用模板元编程实现目标时应该考虑哪些规则?什么是好的例如,使用模板元编程比普通旧代码更有效率,比如boost模板元编程规则

回答

2

我能想到的一个非常有用的规则是尽可能将“编译错误”尽可能接近“真实”问题。通过这种方式,不仅可以推导出问题,而且对于那些使用库来推断问题的人也更容易。

这里是什么,我的意思是一个人为的版本:

template<typename Type> struct convert{}; 
template<> struct convert<double>{ static const int value = D_COORD; }; 
template<> struct convert<Degree>{ static const int value = ANGLE_COORD; }; 
template<> struct convert<Radian>{ static const int value = RADIAN_COORD; }; 

,而您会得到编译器错误的不作为显着的说明企图convert<int>时,如果你只是简单地做了第一个声明向前声明,那么它会立即告诉你,没有为“转换”定义的类型。

就一个很好的例子,恐怕我不得不服从别人。但是,你可能想看看Loki。这不是提升,但它确实很棒。