gpt4 book ai didi

c++ - 将整数常量映射到类型

转载 作者:行者123 更新时间:2023-12-02 09:53:54 26 4
gpt4 key购买 nike

我正在经历Alexandrescu's book它演示了典型整数值以允许编译时调度的有用概念:

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++ 实现?当函数的参数列表中有多个标志可以切换时,可以很好地扩展。

最佳答案

就在这里。这个想法是使用类型而不是 bool (或数字)表达式。您的案例相当琐碎,但在处理更复杂的属性时很有帮助,并且对以后的扩展更加开放。

我将添加另一个虚构的弹性类型“Alien”,只是为了演示扩展。

考虑一下:

// 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{});
}
};

关于c++ - 将整数常量映射到类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62008009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com