中模拟ML样式的模式匹配

中模拟ML样式的模式匹配

标题几乎说明了所有内容,例如,我将如何在C++中模拟ML样式的模式匹配;

Statement *stm;
match(typeof(stm))
{
    case IfThen: ...
    case IfThenElse: ...
    case While: ...
    ...
}

其中“IfThen”,“IfThenElse”和“While”是从“Statement”继承的类

最佳答案

C++委员会最近有一篇论文,描述了允许这样做的库:

Stroustup,Dos Reis和Solodkyy的C++开放高效类型切换
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3449.pdf

带有源代码的页面链接:
https://parasol.tamu.edu/~yuriys/pm/

免责声明:我没有尝试编译或使用此库,但它似乎适合您的问题。

这是该库提供的样本之一:

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

这真是干净!

该库的内部看起来有些吓人。我快速浏览了一下,似乎有很多高级宏和元编程。

关于c++ - 在C++中模拟ML样式的模式匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18197229/

10-10 03:33