iouvxz iouvxz - 3 months ago 19
C++ Question

Can't make the decltype specifier work properly inside the lambda function

This piece of code doesn't complie .The compiler remind me that :cannot convert from “initializer list” to “

std::priority_queue<int, std::vector<_Ty, std::allocator<_Ty>>, std::less<_Ty>> &
”.

#include <vector>
#include <queue>

int main()
{
using namespace std;
priority_queue<int> que;
auto func = [&]()
{
vector<int> vec;
que = decltype(que)(vec.begin(),vec.end());
//cannot convert from“initializer list”to“std::priority_queue<int, std::vector<_Ty, std::allocator<_Ty>>, std::less<_Ty>> &”
};
func();
return 0;
}


If I move the priority_queue declaration into the lambda function ,it compiles perfectly .

#include <vector>
#include <queue>

int main()
{
using namespace std;
auto func = [&]()
{
priority_queue<int> que;
vector<int> vec;
que = decltype(que)(vec.begin(),vec.end());
};
func();
return 0;
}


My compiler is the vs2015 community .

Answer

This looks like a bug. For some reason, decltype(que) evaluates to std::priority_queue<int>& instead of std::priority_queue<int>, which causes the error. This may be related to the fact that que is passed as reference from within the lambda capture list.

You could also make a mutable lambda:

auto func = [que]() mutable
{
    vector<int> vec;
    que = decltype(que)(vec.begin(), vec.end());
};