18

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

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

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

4

1 回答 1

20

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

这是令人惊讶的干净!

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

于 2013-08-13T14:33:10.213 回答