Andrey Komisarov
Andrey Komisarov

Reputation: 105

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;};

Upvotes: 0

Views: 140

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22394

min is a name of a function, not a type. The type of min is 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:

list_heap<int, decltype(min)> rr;

If you cannot edit main, the only other option is to change min into function object:

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

Make sure you don't have using namespace std; in your code or std::min might collide with your own min.

Upvotes: 1

Related Questions