Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Actually, things got much easier in C++11 thanks to the <code>decltype</code> and late return bindings machinery.</p> <p>Now, it's just simpler to use methods to test this:</p> <pre><code>// Culled by SFINAE if reserve does not exist or is not accessible template &lt;typename T&gt; constexpr auto has_reserve_method(T&amp; t) -&gt; decltype(t.reserve(0), bool()) { return true; } // Used as fallback when SFINAE culls the template method constexpr bool has_reserve_method(...) { return false; } </code></pre> <p>You can then use this in a class for example:</p> <pre><code>template &lt;typename T, bool b&gt; struct Reserver { static void apply(T&amp; t, size_t n) { t.reserve(n); } }; template &lt;typename T&gt; struct Reserver &lt;T, false&gt; { static void apply(T&amp; t, size_t n) {} }; </code></pre> <p>And you use it so:</p> <pre><code>template &lt;typename T&gt; bool reserve(T&amp; t, size_t n) { Reserver&lt;T, has_reserve_method(t)&gt;::apply(t, n); return has_reserve_method(t); } </code></pre> <p>Or you can choose a <code>enable_if</code> method:</p> <pre><code>template &lt;typename T&gt; auto reserve(T&amp; t, size_t n) -&gt; typename std::enable_if&lt;has_reserve_method(t), bool&gt;::type { t.reserve(n); return true; } template &lt;typename T&gt; auto reserve(T&amp; t, size_t n) -&gt; typename std::enable_if&lt;not has_reserve_method(t), bool&gt;::type { return false; } </code></pre> <p>Note that this switching things is actually not so easy. In general, it's much easier when just SFINAE exist -- and you just want to <code>enable_if</code> one method and not provide any fallback:</p> <pre><code>template &lt;typename T&gt; auto reserve(T&amp; t, size_t n) -&gt; decltype(t.reserve(n), void()) { t.reserve(n); } </code></pre> <p>If substitution fails, this method is removed from the list of possible overloads.</p> <p><em>Note: thanks to the semantics of <code>,</code> (the comma operator) you can chain multiple expressions in <code>decltype</code> and only the last actually decides the type. Handy to check multiple operations.</em></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. 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