iouvxz
iouvxz

Reputation: 163

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 .

Upvotes: 1

Views: 106

Answers (2)

AndyG
AndyG

Reputation: 41100

This appears to be a MSVC specific compiler error. Assignment isn't allowed because que is a priority_queue<int>&, use std::remove_reference to fix it:

#include <vector>
#include <queue>

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

Upvotes: 4

Rakete1111
Rakete1111

Reputation: 48948

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

Upvotes: 1

Related Questions