c++ - 为什么这个语句 `priority_queue <pair<int,int>, vector<pair<int,int>>,compare>pq;` 在 C++03 中是错误的,但在 C++11 中是正确的?

标签 c++ templates

以下代码片段声明了一个 pair<int,int> 类型的 priority_queue。并使用类比较器并在 C++11 中正确,但在 C++03 中显示错误。这是什么原因?

class compare
    {
    public:

        bool operator () (pair<int,int>&p1,pair<int,int>&p2)
        {
            return p1.second > p2.second;
        }
    };
    priority_queue <pair<int,int>, vector<pair<int,int> >,compare>pq;    

C++03 编译器显示:

  • 错误:“模板类 std::priority_queue”的模板参数使用本地类型“main()::compare” priority_queue , vector >,compare>pq;
  • 错误:试图实例化“模板类 std::priority_queue”

最佳答案

在 C++11 之前,不可能将本地类型作为模板参数传递。

这就是您的 C++03 编译器拒绝该代码的原因。

如果您使用的是现代编译器,则可以将其转换为 C++11 或 C++14 模式。
否则,你就不走运了。


[C++11: C.2.6]: Clause 14: templates

[..]

14.6.4.2
Change: Allow dependent calls of functions with internal linkage
Rationale: Overly constrained, simplify overload resolution rules.
Effect on original feature: A valid C++ 2003 program could get a different result than this International Standard.

关于c++ - 为什么这个语句 `priority_queue <pair<int,int>, vector<pair<int,int>>,compare>pq;` 在 C++03 中是错误的,但在 C++11 中是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36019183/

相关文章:

javascript - 使用模块导出将模板文字与逻辑分开

C++ 模板类型转换与导数

C++:模板代码在 clang++ 下编译和运行良好,但在 g++ 下失败

c++ - 意外#else

c++ - 到达流的 EOF 时,seekg() 不会设置 eofbit。是设计使然吗?

C++ 模板实例化限制

c++ - 如何区分具有非类型参数的模板重载?

c++ - 如何计算 OpenCV 中图像中的提示数?

c++ - 使用 std::async 比非异步方法慢来填充 vector

c++ - 将二维数组传递给 C++ 中的函数时出错