c++ - 无法使 decltype 说明符在 lambda 函数内正常工作

标签 c++ c++11 lambda grammar decltype

这段代码不符合。编译器提醒我:无法从“初始化列表”转换为“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;
    }

如果我将 priority_queue 声明移动到 lambda 函数中,它会完美编译。

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

我的编译器是vs2015社区。

最佳答案

这似乎是 MSVC 特定的编译器错误。不允许分配,因为 quepriority_queue<int>& , 使用 std::remove_reference修复它:

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

关于c++ - 无法使 decltype 说明符在 lambda 函数内正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39183239/

相关文章:

c++ - C++ 中的整数到字符串转换/整数字符串连接 - 更紧凑的解决方案?

c++ - 派生类的继承方法不起作用

c++ - 是否可以根据基于范围的 for 类型调用不同的取消引用运算符重载

python - python 中是否有与 Linq.Expressions.Expression 等效的东西?

c++ - 在 lambda 中捕获对齐变量时出现段错误

c++ - 在 cpp 中重载 << 运算符的正确方法是什么

c++ - union 对象就像一个结构

c++ - 编译时 x86_64 的 undefined symbol

c++ - 嵌套 std::array 时结构初始值设定项中的多余元素

java - 使用 Mockito 为 Java 8 lambda 表达式编写 stub