Note that there are some explanatory texts on larger screens.

plurals
  1. POConfusing function lookup with templates in C++
    primarykey
    data
    text
    <p>Starting with the following (using <code>gcc version 4.0.1</code>):</p> <pre><code>namespace name { template &lt;typename T&gt; void foo(const T&amp; t) { bar(t); } template &lt;typename T&gt; void bar(const T&amp; t) { baz(t); } void baz(int) { std::cout &lt;&lt; "baz(int)\n"; } } </code></pre> <p>If I add (in the <em>global</em> namespace)</p> <pre><code>struct test {}; void bar(const test&amp;) { std::cout &lt;&lt; "bar(const test&amp;)\n"; } </code></pre> <p>then, as I expected,</p> <pre><code>name::foo(test()); // produces "bar(const test&amp;)" </code></pre> <p>But if I just add</p> <pre><code>void bar(const double&amp;) { std::cout &lt;&lt; "bar(const double&amp;)\n"; } </code></pre> <p>it can't seem to find this overload:</p> <pre><code>name::foo(5.0) // produces "baz(int)" </code></pre> <p>What's more,</p> <pre><code>typedef std::vector&lt;int&gt; Vec; void bar(const Vec&amp;) { std::cout &lt;&lt; "bar(const Vec&amp;)\n"; } </code></pre> <p>doesn't appear either, so</p> <pre><code>name::foo(Vec()); </code></pre> <p>gives a compiler error</p> <pre><code>error: cannot convert ‘const std::vector&lt;int, std::allocator&lt;int&gt; &gt;’ to ‘int’ for argument ‘1’ to ‘void name::baz(int)’ </code></pre> <p>Is this how the lookup is supposed to work? (Note: if I remove the namespace <code>name</code>, then everything works as I expected.)</p> <p>How can I modify this example so that any overload for <code>bar</code> is considered? (I thought that overloads were supposed to be considered <em>before</em> templates?)</p>
    singulars
    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