类类型名不起作用
Class typename doesn't work
请告诉我什么是错误的代码,我应该改变什么来修复它(我得到编译错误):
#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类型作为模板参数来声明该类,就像您的代码一样:
相关文章:
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用
- C++ 模板类型检查标准::is_same不起作用?
- 没有类型结构绑定不起作用?
- "+=" 操作在类型之间不起作用 std::复杂<double>和__complex__双精度
- 模板 ctor 类型推导不起作用(没有匹配的构造函数用于初始化 ...)与函数<>参数
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 模板参数类型推导在函数对象中不起作用
- 将参考类型作为嵌套模板结构中的模板参数作为模板参数不起作用
- 模板参数在具有相同数据类型的单个类型名的构造函数中不起作用
- 使用具有不同类型不同回报的模板函数不起作用
- 为什么 C++ 从推断的返回类型中去除引用限定符,为什么生存期延长不起作用?
- pybind11:Python 到 C++ 数据类型转换不起作用
- 抽象类型的对象 - 覆盖不起作用吗?
- 完整的模板专用化不起作用:没有与指定类型匹配的函数模板"mysort2"实例 STLests
- lambda函数返回类型不起作用
- 使用初始化列表的 POD 类型初始化不起作用
- StringStream的Str方法将不起作用.(不同类型的串联)(C )
- 为什么我的链接数据类型复制构造函数不起作用?
- std::string 的函数指针的类型定义不起作用