如何将具有不同成员变量类型的两个类和不同的构造函数制作到派生/基类或模板类中?
class Data
{
public:
int i;
};
auto cmp = [](const Data& d1, const Data& d2) { return d1.i > d2.i; };
class A
{
private:
queue<Data> q;
public:
A() {};
void func() {
int cnt = 0;
while (!q.empty()) {
std::cout << cnt++ << std::endl;
q.pop();
}
}
};
class B
{
private:
priority_queue<Data, vector<Data>, decltype(cmp)> q;
public:
B() :q(cmp) {};
void func() {
int cnt = 0;
while (!q.empty()) {
std::cout << cnt++ << std::endl;
q.pop();
}
}
};
我定义了两个类别的A和B. As Shis,他们的成员func
是相同的,但是具有不同的成员变量类型q
和不同的构造函数。
因此,我可以将A和B分为两个基类派生的两个类(但是在基类中使用func
)或将它们放入模板类?(也就是说,我只想写<<代码> func 一次..) 如果可以的话,如何?
class Data
{
public:
int i;
};
auto cmp = [](const Data& d1, const Data& d2) { return d1.i > d2.i; };
class A
{
private:
queue<Data> q;
public:
A() {};
void func() {
int cnt = 0;
while (!q.empty()) {
std::cout << cnt++ << std::endl;
q.pop();
}
}
};
class B
{
private:
priority_queue<Data, vector<Data>, decltype(cmp)> q;
public:
B() :q(cmp) {};
void func() {
int cnt = 0;
while (!q.empty()) {
std::cout << cnt++ << std::endl;
q.pop();
}
}
};
I define two classes A and B.As seen, their member func
is the same, but with different member variable type q
and different constructor.
So could I make A and B into two class derived from one base class (but with func
in base class) or make them into a template class?(That is to say, I only want to write func
once..)
If could, then how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这两种情况下,看来您只是在擦除收集类中的项目数量。如果是这样,让我们保持简单。
或者
我要推荐一种继承策略,其中A和B来自基本模板类。但是在编码之后,我不喜欢从表面上的排队课程中得出的想法。您不能诚实地说A或B是队列的“是”。但这是我写的,我不喜欢它。
一种更好的方法可能只编写一个模板函数:
然后保留您的原始实现:
In both cases, it looks like you are just trying to count the number of items in a collection class before erasing it. If that's the case, let's just keep it simple.
OR
I was about to recommend an inheritance strategy where A and B derived from a Base template class. But after I coded it, I didn't like the idea of deriving from what's ostensibly a queue class. You can't honestly say that A or B are "is a" of a queue. But here's what I wrote and I don't like it.
A better approach might to just write a single template function:
And then keep your original implementations: