用各种语言表示模式的方法

时间:2018-04-01 17:13:36

标签: c++ pattern-matching

我有一些C ++代码。我在其中反复复制一个图案,这是不愉快的。

class layerclass {
public:
  vector<int> a;
  vector<int> b;
  vector<int> c;

  bool isInA(int x) { return a.find(x) != a.end(); } // true if x is in a
  bool isInB ...
  bool isInC ...
};
class innerlayer : public layerclass {
public:
  layerclass *outerlayer;
  bool isInA(int x) {
    if (layerclass::isInA(x)) return true;
    return outerlayer->isInA(x);
  }
  bool isInB(int x) ...  // these two fn's will be identical to isInA()
  bool isInC(int x) ...  // with the exception of calling isInB/C()
};

在我的情况下,确实只有大约3个容器可以用这种方式进行搜索,但是对我来说这很麻烦。解决方案可能是以某种方式标记分发:

class layerclass {
public:
  vector<int> a;
  vector<int> b;
  vector<int> c;
  enum class members { a, b, c };

  bool isIn(int x, members m) { 
    switch (m) {
      case members::a: return a.find(x) != a.end(); 
    ...
  }

};
class innerlayer : public layerclass {
public:
  layerclass *outerlayer;
  bool isIn(int x, member m) {
     if (layerclass::isIn(x, m) return true;
     return outerlayer->isIn(x, m);
  }
};

好的,这有点好,但我仍然在layerclass :: isIn()中有重复的代码,并且必须维护枚举。这是我在C ++中做得最好的吗?其他语言是否提供了一个方便的解决方案,除了预处理器宏之外?

1 个答案:

答案 0 :(得分:2)

您可以按如下方式重写该类,因此isIn

中没有重复的代码
class layerclass {
public:
    vector<int> a;
    vector<int> b;
    vector<int> c;
    bool isIn(vector<int> &vec, int x) { return vec.find(x) != a.end(); }
    bool isInA(int x) { return isIn(a, x); }
    bool isInB(int x) { return isIn(b, x); }
    bool isInC(int x) { return isIn(c, x); }
};