Simulating ML-style pattern matching in C++

前端 未结 1 1315
一个人的身影
一个人的身影 2021-01-01 18:34

The title says pretty much all, how would I go about simulating ML-style pattern matching in C++, that is for instance;

Statement *stm;
match(typeof(stm))
{
         


        
相关标签:
1条回答
  • 2021-01-01 19:04

    There was a paper in the C++ committee recently which describe a library that allow to do just that:

    Open and Efficient Type Switch for C++ by Stroustup, Dos Reis and Solodkyy
    http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3449.pdf

    A link to a page with source code :
    https://parasol.tamu.edu/~yuriys/pm/

    Disclaimer : I didn't try to compile or use this library, but it seem to fit your question.

    Here is one of the sample provided by the library :

    #include <utility>
    #include "match.hpp"                // Support for Match statement
    
    //------------------------------------------------------------------------------
    
    typedef std::pair<double,double> loc;
    
    // An Algebraic Data Type implemented through inheritance
    struct Shape
    {
        virtual ~Shape() {}
    };
    
    struct Circle : Shape
    {
        Circle(const loc& c, const double& r) : center(c), radius(r) {}
        loc    center;
        double radius;
    };
    
    struct Square : Shape
    {
        Square(const loc& c, const double& s) : upper_left(c), side(s) {}
        loc    upper_left;
        double side;
    };
    
    struct Triangle : Shape
    {
        Triangle(const loc& a, const loc& b, const loc& c) : first(a), second(b), third(c) {}
        loc first;
        loc second;
        loc third;
    };
    
    //------------------------------------------------------------------------------
    
    loc point_within(const Shape* shape)
    {
        Match(shape)
        {
           Case(Circle)   return matched->center;
           Case(Square)   return matched->upper_left;
           Case(Triangle) return matched->first;
           Otherwise()    return loc(0,0);
        }
        EndMatch
    }
    
    int main()
    {
        point_within(new Triangle(loc(0,0),loc(1,0),loc(0,1)));
        point_within(new Square(loc(1,0),1));
        point_within(new Circle(loc(0,0),1));
    }
    

    This is surprisingly clean !

    The internals of the library looks a bit more scary though. I did a quick glance and there seems to be quite a lot of advanced macro and meta-programing.

    0 讨论(0)
提交回复
热议问题