Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand the question correctly, I actually think something like this is possible using a function overload. <a href="http://www.altdevblogaday.com/2011/10/27/quasi-compile-time-string-hashing/" rel="nofollow">Here's an article</a> that shows the basic idea. In your case I think it would be sufficient to have the following two overloads:</p> <pre><code>void f(char const *); template&lt;unsigned int N&gt; void f(char const (&amp;)[N]); </code></pre> <p>The latter should be invoked when the string is a string literal, the latter at other times. If the compiler is sufficiently good at optimizing then calls to the latter may be evaluated at compile time.</p> <p>EDIT:</p> <p>Alright, it bothered me that the above solution didn't work, so I did some playing around and I think I came up with a solution:</p> <pre><code>#include &lt;string&gt; #include &lt;boost/utility/enable_if.hpp&gt; template&lt;typename T&gt; struct is_string_literal { enum { value = false }; }; template&lt;unsigned int N&gt; struct is_string_literal&lt;char const (&amp;)[N]&gt; { enum { value = true }; }; template&lt;typename T&gt; typename boost::disable_if&lt;is_string_literal&lt;T&gt; &gt;::type foo(T) { std::cout &lt;&lt; "foo1" &lt;&lt; std::endl; } template&lt;int N&gt; void foo(char const (&amp;)[N]) { std::cout &lt;&lt; "foo2" &lt;&lt; std::endl; } int main( ) { std::string bar = "blah"; char const str[] = "blah"; foo(str); foo("blah"); foo(bar.data()); } </code></pre> <p>The output (on GCC 4.4 with -O3) is:</p> <pre><code>foo2 foo2 foo1 </code></pre> <p>I admit that I don't completely understand why this works when the previous solution didn't. Maybe there's something about overload resolution that I don't completely understand.</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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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