类类型名不起作用

Class typename doesn't work

本文关键字:不起作用 类型      更新时间:2023-10-16

请告诉我什么是错误的代码,我应该改变什么来修复它(我得到编译错误):

#include <algorithm>
#include <cstring>
using namespace std;
const int MMAX = 1000001;

//--------------------------------------------------------------------------------------------
    inline bool comp(int &A, int &B) {
        if (A < B) return true;
        return false;
    }
template<typename _CompareFunction>
    struct myHeap { // min-heap
    _CompareFunction cmp;
    };
//--------------------------------------------------------------------------------------------
myHeap< comp > H;
int main() {
}

提前感谢!

编辑:编译错误:

heap_minimal.cpp:19:15: error: type/value mismatch at argument 1 in template parameter list for ‘template<class _CompareFunction> struct myHeap’
heap_minimal.cpp:19:15: error:   expected a type, got ‘comp’
heap_minimal.cpp:19:18: error: invalid type in declaration before ‘;’ token

(用c++ 11编译)

myHeap< comp > H;

你应该传递一个类型作为模板参数,而不是一个函数。将声明更改为以下内容:

myHeap<std::function<bool(int&, int&)>> H{comp};

myHeap<decltype(comp)*> H{comp};

如果你想只传递模板参数(不传递函数),你应该用重载的operator()声明MyComp类:

struct MyComp
{
    bool operator() (int &A, int &B)
    {
        // if (A < B) return true;
        // return false;
        return A < B;
    }
};

然后传递参数:

myHeap<MyComp> H;

这里的问题是,在模板定义

template<typename _CompareFunction>

_CompareFunction是一个类型,但随后您尝试在其中使用comp 函数。但是你需要一个类型,所以你可以像这样修复错误:

myHeap< bool (*)(int&, int&) > H;

可以工作,因为bool (*)(int&, int&)是comp函数的一种类型。或者,您可以定义myHeap以一个函数作为模板参数

template <bool (*fun)(int&, int&)>
struct myHeap2 
{      
};

然后你可以像这样使用

myHeap2<comp> H2;

您应该使用"typedef bool (*comp)(int&, int&);"语句定义类型,然后通过传递comp类型作为模板参数来声明该类,就像您的代码一样: