Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to legally overload a string literal and const char*?
    primarykey
    data
    text
    <p>Is it possible in C++11 to overload <code>const char*</code>'s and string literals (<code>const char[]</code>)? The idea is to avoid having to call <code>strlen</code> to find the string length when this length is known already.</p> <p>This snippet breaks on G++ 4.8 and Clang++ 3.2:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; template&lt;typename T, int N&gt; void length(const T(&amp;data)[N]) { printf("%u[]\n", N - 1); } template&lt;typename T&gt; void length(const T* data) { printf("*%u\n", (unsigned)strlen(data)); } int main() { length("hello"); const char* p = "hello"; length(p); return 0; } </code></pre> <p>Error (Clang):</p> <pre><code>test2.cpp:16:3: error: call to 'length' is ambiguous length("hello"); ^~~~~~ test2.cpp:6:6: note: candidate function [with T = char, N = 6] void length(const T(&amp;data)[N]) { ^ test2.cpp:11:6: note: candidate function [with T = char] void length(const T* data) { ^ 1 error generated. </code></pre> <p>Hacked a bit, and this appears to work:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; template&lt;typename T, int N&gt; void length(const T(&amp;data)[N]) { printf("%u[]\n", N - 1); } template&lt;typename T&gt; void length(T&amp;&amp; data) { printf("*%u\n", (unsigned)strlen(data)); } const char *foo() { return "bar"; } int main() { length("hello"); const char* p = "hello"; length(p); length(foo()); return 0; } </code></pre> <p>Is this valid C++11? The string literal appears to overload on <code>T&amp;&amp;</code> when the array specialization is removed. What causes this ambigousness to be resolved, but not the one in the first code snippet?</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