我正在经历 Alexandrescu的书 它展示了将积分值类型化以允许编译时调度的有用概念。
template <int Val>
struct Elastic
{
enum {V = Val};
};
template <class Object, bool isElastic>
class ImpactMomentum
{
double calc_momentum(double v_in, Elastic<true> /* */)
{
// compute elastic ...
}
double calc_momentum(double v_in, Elastic<false> /* */)
{
// compute rigid ...
}
public:
double calc_momentum(double v_in)
{
calc_velocity(v_in, Elastic<isElastic>());
}
};
有没有一个现代的C++实现可以取代这个习惯?当函数的参数列表中有多个标志需要切换时,有什么东西可以很好地扩展。
是的,是有的。 我们的想法是用类型代替布尔(或数值)表达式。 你的情况比较琐碎,但在处理比较复杂的属性时很有帮助,而且对以后的扩展比较开放。
我再加一个想象中的弹性类型 "外星人",只是为了演示扩展。
考虑一下这个问题。
// empty types
struct Elastic { enum {V = Val}; };
struct Rigid {};
struct Alien {};
template <class Object, class Elasticity>
class ImpactMomentum
{
// for libraries wanting to give users even more expansion options,
// without modifying the library, these specializations could be
// regular free functions also taking *this as a parameter, for
// example.
double calc_momentum(double v_in, Elastic) // or const & if property has data
{
// ...
}
double calc_momentum(double v_in, Rigid)
{
// ...
}
double calc_momentum(double v_in, Alien)
{
// ...
}
public:
double calc_momentum(double v_in)
{
return calc_velocity(v_in, Elasticity{});
}
};