Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I write a function template for all types with a particular type trait?
    primarykey
    data
    text
    <p>Consider the following example:</p> <pre><code>struct Scanner { template &lt;typename T&gt; T get(); }; template &lt;&gt; string Scanner::get() { return string("string"); } template &lt;&gt; int Scanner::get() { return 10; } int main() { Scanner scanner; string s = scanner.get&lt;string&gt;(); int i = scanner.get&lt;int&gt;(); } </code></pre> <p>The <code>Scanner</code> class is used to extract tokens from some source. The above code works fine, but fails when I try to <code>get</code> other integral types like a <code>char</code> or an <code>unsigned int</code>. The code to read these types is exactly the same as the code to read an <code>int</code>. I could just duplicate the code for all other integral types I'd like to read, but I'd rather define one function template for all integral types.</p> <p>I've tried the following:</p> <pre><code>struct Scanner { template &lt;typename T&gt; typename enable_if&lt;boost::is_integral&lt;T&gt;, T&gt;::type get(); }; </code></pre> <p>Which works like a charm, but I am unsure how to get <code>Scanner::get&lt;string&gt;()</code> to function again. So, how can I write code so that I can do <code>scanner.get&lt;string&gt;()</code> and <code>scanner.get&lt;any integral type&gt;()</code> and have a single definition to read all integral types?</p> <p><strong>Update: bonus question</strong>: What if I want to accept more than one range of classes based on some traits? For example: how should I approach this problem if I want to have three <code>get</code> functions that accept (i) integral types (ii) floating point types (iii) strings, respectively.</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.
 

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