Pratik Singhal
Pratik Singhal

Reputation: 6492

What is the use of decltype in this code ?

I have a written a small piece of code which throws a lot of error, If I dont't use the decltype keyword while with the decltype keyword it compiles fine : -

   std::function<bool(int,int)> f2 = [dist](int n1,int n2) {if(dist[n1] < dist[n2]) return false ; return true ; } ; 
        priority_queue<int,vector<int>,decltype(f2)>  pq(f2)  ; 

Here, I wanted to declare a priority_queue with my own custom comparison function, so I decided to use std::function and lambdas.
Also, dist is a std::vector<int>

But strangely , the code gives error if I replace decltype(f2) with just f2.

Why is is so ?

Upvotes: 0

Views: 233

Answers (3)

Vul
Vul

Reputation: 44

I don't know why you use this std::function<bool(int,int)> as your return type for your lambda function, I would use simply auto instead since std::function may also offer some overhead during type construction. Let the compiler make its best choice for you if you don't know what it does.

Upvotes: -1

Arashium
Arashium

Reputation: 325

Referring to documentations, priority_queue must receive 3 types. Here, types int and vector<int> are followed by the type of f2 and not f2. decltype gives you a type not a variable.

Note that: decltype = typeof but in official way

Upvotes: 2

ForEveR
ForEveR

Reputation: 55887

Third parameter of priority_queue template class is type of predicate. Here decltype(f2) actually gives a type of f2, instead decltype you can just write std::function<bool(int,int)>.

Upvotes: 3

Related Questions