用各种语言表示模式的方法
Ways to represent pattern in various languages
我有一些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); }
};
相关文章:
- c++方法参数只能在linux的发布模式下自行更改
- 使用模板而不是虚拟方法的管道模式
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- 在C++中创建观察器设计模式的好方法
- 工厂方法模式使用继承而抽象工厂模式使用组合如何
- 是否有可以处理方法调用依赖关系的设计模式?
- 设计模式中对象中的过程(方法和操作)的状态
- 用各种语言表示模式的方法
- 在数组中查找模式的最有效方法?
- 设计模式的工厂替代方法:具有不同构造函数的类
- C++,在阻塞模式下从套接字读取所有可用字节的最佳方法
- 正确的方法或设计模式,以简化类中的“operatorX”函数,以按给定顺序比较相同类型的属性
- 返回不同类型/类的方法的设计模式
- 如何将策略模式与派生类中的其他方法一起使用
- 类型擦除和一种模板方法模式
- 对不同的参数使用工厂方法模式
- 一种在 Mac 上强制关闭模式 QFileDialog 的方法
- dlopen、工厂模式和虚拟方法表
- 工厂模式和std::绑定方法
- 找到数据集C 模式的更好方法