简体   繁体   English

模板中的类型名和变量

[英]Typename and variable in templates

I want to do structure with some type and with ability to use another comparator somewhen.This way of do template is not work.How I can do it correct?我想用某种类型来做结构,并且有能力在某个时候使用另一个比较器。这种做模板的方式是行不通的。我该如何正确地做?

template<typename T, typename Comparator = std::less<T>>
struct list_heap{};
bool min(int &a, int &b){return a<b;};
int main(){list_heap<int>r;list_heap<int, min>rr;return 0;};

min is a name of a function, not a type. min是 function 的名称,而不是类型。 The type of min is bool(*)(int&, int&) . min的类型是bool(*)(int&, int&)

You can initialize your struct by giving the full type name:您可以通过提供完整的类型名称来初始化您的结构:

list_heap<int, bool(*)(int&, int&)> rr;
//or something that bool(*)(int&, int&) will be convertible to:
list_heap<int, std::function<bool(int&, int&)>> rr;

Or by utilizing decltype to let compiler deduce the type:或者利用decltype让编译器推断类型:

list_heap<int, decltype(min)> rr;

If you cannot edit main , the only other option is to change min into function object:如果您无法编辑main ,唯一的其他选择是将min更改为 function object:

struct min
{
    bool operator()(int &a, int &b){return a<b;};
};

Make sure you don't have using namespace std;确保你没有using namespace std; in your code or std::min might collide with your own min .在您的代码或std::min中可能会与您自己的min发生冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM