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

Ways to represent pattern in various languages

本文关键字:模式 方法 表示 语言      更新时间:2023-10-16

我有一些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 中所做的最好的?其他语言是否为此类内容提供了方便的解决方案,例如预处理器宏?

您可以如下重写类,因此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); }
};