Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this std::sort predicate fail when the class is inside main()?
    primarykey
    data
    text
    <p>This is a much simplified repro which illustrates how <code>class Predicate</code> delcared outside <code>main()</code> works but when the exact code appears inline as <code>class InlinePredicate</code> the compiler can't match <code>std::sort</code>. The strange thing is that you can pass <em>anything</em> as the third argument to <code>std::sort</code> (say, integer 7) and you'll just get a compile error when it does not support the <code>operator ()</code> that <code>sort</code> expects. But when I pass <code>pred2</code> below it doesn't match at all:</p> <pre><code>#include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; using namespace std; class Predicate { public: bool operator () (const pair&lt;string,int&gt;&amp; a, const pair&lt;string,int&gt;&amp; b) { return a.second &lt; b.second; } }; int main() { vector&lt;pair&lt;string, int&gt; &gt; a; Predicate pred; sort(a.begin(), a.end(), pred); class InlinePredicate { public: bool operator () (const pair&lt;string,int&gt;&amp; a, const pair&lt;string,int&gt;&amp; b) { return a.second &lt; b.second; } } pred2; sort(a.begin(), a.end(), pred2); return 0; } </code></pre> <blockquote> <p>repro.cc: In function ‘int main()’:</p> <p>repro.cc:30: error: no matching function for call to ‘sort(__gnu_cxx::__normal_iterator, std::allocator >, int>*, std::vector, std::allocator >, int>, std::allocator, std::allocator >, int> > > >, __gnu_cxx::__normal_iterator, std::allocator >, int>*, std::vector, std::allocator >, int>, std::allocator, std::allocator >, int> > > >, main()::InlinePredicate&amp;)’</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload