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

标签 c++ c++11 c++14 c++17

我正在经历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/

相关文章:

c++ - 使用C++在打印机上打印pdf文件

c++全局/堆栈实例ctor/dtor在调用静态函数时崩溃

c++ - "duplicate data type in declaration"是什么意思?

c++ - 我们可以使用类似 c++1y std::tie() 的函数进行深度绑定(bind)吗?

C++ countof 成员数组的实现

c++ - 如何定义指向 const 对象的可变指针?

c++ - 迭代 vector 以更新 word_counter

c++ - 为什么下面的 initializer_list 函数失败了?

c++ - C++中的最大线程数

c++ - 返回类型自动扣除的好友函数模板无法访问私有(private)成员