在C++中,如何模板化一个类以使用另一个类和该类的成员

In C++, how do I template a class to use another class and a member of that class?

本文关键字:另一个 成员 一个 C++ 何模板      更新时间:2023-10-16

所以我希望能够在不同情况下使用我们为家庭作业设计的数据结构。具体来说,我有一个 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();
    }
};
相关文章: