Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In addition to the other answers, it should be noted that the test can be used at runtime but also at compile-time to select the correct implementation depending on wether the type is integral or not:</p> <p>Runtime version:</p> <pre><code>// Include either &lt;boost/type_traits/is_integral.hpp&gt; (if using Boost) // or &lt;type_traits&gt; (if using c++1x) // In the following, is_integral shoudl be prefixed by either boost:: or std:: template &lt;typename T&gt; void algorithm(const T &amp; t) { // some code if (is_integral&lt;T&gt;::value) { // operations to perform if T is an integral type } else { // operations to perform if T is not an integral type } // some other code } </code></pre> <p>However, this solution can be improved when the implementation of the algorithm greatly depends on the test. In this case, we would have the test at the top of the function, then a big <code>then</code> block and a big <code>else</code> block. A common approach in this case is to overload the function and make the compiler select the correct implementation using SFINAE. An easy way to do this is to use <a href="http://www.boost.org/doc/libs/1_42_0/libs/utility/enable_if.html" rel="nofollow noreferrer"><code>boost::enable_if</code></a>:</p> <pre><code>#include &lt;boost/utility/enable_if.hpp&gt; #include &lt;boost/type_traits/is_integral.hpp&gt; template &lt;typename T&gt; typename boost::enable_if&lt;boost::is_integral&lt;T&gt; &gt;::type algorithm(const T &amp; t) { // implementation for integral types } template &lt;typename T&gt; typename boost::disable_if&lt;boost::is_integral&lt;T&gt; &gt;::type algorithm(const T &amp; t) { // implementation for non integral types } </code></pre> <p>When invoking the <code>algorithm</code> function, the compiler will "select" the correct implementation depending on wether the template parameter is integral or not.</p>
    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.
    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.
    3. 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