Mansoor
Mansoor

Reputation: 2438

Mapping integral constants to types

I am going through Alexandrescu's book and it demonstrates the useful concept of typifying integral values to allow for compile-time dispatch:

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>());
    }
};

Is there a modern C++ implementation which supersedes this idiom? Something which scales well when there are multiple flags to toggle in the function's argument list.

Upvotes: 1

Views: 202

Answers (1)

Micha&#235;l Roy
Micha&#235;l Roy

Reputation: 6471

Yes, there is. The idea is to use type instead of boolean (or numerical) expressions. Your case is rather trivial, but it is helpful when dealing with more complex properties, and is more open for later expansion.

I'll add another imaginary elasticity type "Alien", only for the sake of demonstratring expansion.

Consider this:

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

Upvotes: 3

Related Questions