模板元编程经验法则

时间:2011-02-27 13:08:55

标签: c++ templates metaprogramming rules

当有人使用模板元编程来实现目标时,应该考虑哪些经验法则?什么是示例,使用模板元编程比使用 boost 等库以外的普通旧代码更有效?

1 个答案:

答案 0 :(得分: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。它不是提升,但确实很棒。