在C++中,如何模板化一个类以使用另一个类和该类的成员
In C++, how do I template a class to use another class and a member of that class?
所以我希望能够在不同情况下使用我们为家庭作业设计的数据结构。具体来说,我有一个 minHeap,但我想模板化它来获取对象。由于 minHeap 必须比较元素以保持结构并有效地返回最小值,是否可以模板化我的 minHeap 类以将任何给定对象和该对象的成员作为元素之间比较的东西?
我的想法是这样的:
template<class TYPE, class TYPE_COMPARE>
class minHeap {
...(stuff inside)...
};
但我意识到我无法使用 TYPE_COMPARE 真正访问 TYPE 类型的对象中的某些内容。这就是为什么我想知道我是否可以模板化一个类来接受另一个类和该类的成员。
编辑:有人建议添加我的代码进行澄清。这就是我想象的样子,但我有一种强烈的感觉,它不是这样工作的。
这是我的 minHeap 的头文件。
#include <vector>
using namespace std;
template<class TYPE, TYPE::class MEMBER>
class minHeap {
private:
vector<TYPE> nodes;
int current;
int parent(int i) {
return (i-1)/2;
}
int leftChild(int i) {
return 2*i+1;
}
int rightChild(int i) {
return 2*i+2;
}
void bubbleUp(int i) {
if(i > 0) {
int p = parent(i);
if(nodes[i]::MEMBER < nodes[p]::MEMBER) {
swap(nodes[i], nodes[p]);
bubbleUp(p);
}
}
}
void bubbleDown(int i) {
if(i < current) {
int a = leftChild(i);
int b = rightChild(i);
if(b > current && a <= current) {
if(nodes[i]::MEMBER > nodes[a]::MEMBER) {
swap(nodes[i], nodes[a]);
}
}
else if(b <= current && a <= current) {
if(nodes[i]::MEMBER > nodes[a]::MEMBER || nodes[i]::MEMBER > nodes[b]::MEMBER) {
if(nodes[a] < nodes[b]) {
swap(nodes[i], nodes[a]);
bubbleDown(a);
}
else {
swap(nodes[i], nodes[b]);
bubbleDown(b);
}
}
}
}
}
public:
minHeap() {
current = -1;
}
void insert(TYPE x) {
current++;
nodes.push_back(x);
bubbleUp(current);
}
TYPE extractMin() {
TYPE min = nodes[0];
swap(nodes[0], nodes[current]);
current--;
nodes.pop_back();
bubbleDown(0);
return min;
}
bool empty() {
if(current < 0)
return true;
return false;
}
};
您当然可以访问TYPE
。但由于您只有类型,因此只能访问静态成员。
class MyType
{
static void SomeStaticFunction();
};
template<class TYPE>
class minHeap
{
void fn()
{
TYPE::SomeStaticFunction();
}
};
如果要访问非静态成员,则自然需要一个实例来操作:
class MyType
{
void SomeNonStaticFunction();
};
template<class TYPE>
class minHeap
{
void fn(const TYPE& inst)
{
inst.SomeNonStaticFunction();
}
};
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 访问从联合与另一个成员集复制的联合中的一个成员是否未定义或未指定?
- 使用线程从另一个成员函数调用一个Member函数
- 如何通过指针将模板成员函数传递给另一个成员函数
- 初始化指针或引用成员变量以指向另一个成员
- 在另一个成员函数中调用成员函数时'int'之前的预期主表达式
- C 将成员函数作为参数传递给另一个成员函数
- 如何在另一个成员函数中修改具有常量返回类型的成员函数的返回值
- 从其后声明的另一个成员数据初始化成员数据是否为未定义行为
- 如何使一个成员变量等于在main()中设置的另一个成员变量
- 在另一个成员中动态添加类成员
- 将类成员函数作为参数从同一类的另一个成员函数传递
- 将成员函数指针作为另一个成员函数中的参数发送
- 如何从同一类的另一个成员函数调用函子
- 从另一个成员函数的实现调用成员函数
- 如何将带有 args 的成员函数作为参数传递给另一个成员函数
- C++ 成员函数错误 在另一个成员函数中使用时"Undeclared Identifier"
- 如何根据其中一个成员的值对结构数组进行排序,从而在另一个成员的基础上断开联系
- 初始化整数成员变量会导致更改另一个成员变量的地址