简体   繁体   中英

Why this statement `priority_queue <pair<int,int>, vector<pair<int,int> >,compare>pq;` is an error in C++03 but correct in C++11?

The following code fragment declares a priority_queue of type pair<int,int> and uses a class comparator and correct in C++11 but shows error in C++03. What is the reason?

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 compiler shows:

  • error: template argument for 'template class std::priority_queue' uses local type 'main()::compare' priority_queue , vector >,compare>pq;
  • error: trying to instantiate 'template class std::priority_queue'

Before C++11, it was impossible to pass local types as template arguments.

That's why your C++03 compiler rejects the code.

If you're using a modern compiler, you can flip it into C++11 or C++14 mode.
Otherwise, you're out of luck.


[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM