Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to change a template method based on whether the type is an integral or floating point type?
    primarykey
    data
    text
    <p>I'm working on a Matrix class which takes both integral (short, int, long) and floating point types (float, double). I want some methods to be restricted to only floating point types (such as the inversion method) and some methods to have different implementations for floating types and integral types (such as the == operator). I have a hunch the right way is to use boost's "enable_if" and "is_integral" / "is_floating_point", but I can't seem to get it to work. </p> <p>My implementation is something similar to this c++ semi-pseudo code:</p> <pre><code>template &lt;typename T&gt; class Matrix { ... bool operator==(Matrix&lt;typename enable_if&lt;is_integral&lt;T&gt; T &gt;::type &gt;) const; bool operator==(Matrix&lt;typename enable_if&lt;is_floating_point&lt;T&gt;::type T&gt; &gt;) const; typename enable_if&lt;is_floating_point&lt;T&gt; T&gt; computeInverse() const; ... }; // implementation bool Matrix&lt;T&gt;::operator==(Matrix&lt;typename enable_if&lt;is_integral&lt;T&gt; T &gt;::type &gt;) const { //implementation without precision } bool Matrix&lt;T&gt;::operator==(Matrix&lt;typename enable_if&lt;is_integral&lt;T&gt; T &gt;::type &gt;) const { //implementation using precision } Matrix&lt;typename enable_if&lt;is_floating_point&lt;T&gt; T&gt;::type &gt; Matrix&lt;T&gt;::computeInverse() const { //implementation requiring floating points } </code></pre> <p>This produces a lot of compile errors, whereas I think these are the most relevant ones:</p> <pre><code>error: no type named ‘type’ in ‘struct boost::enable_if&lt;boost::is_integral&lt;float&gt;, float&gt;’ </code></pre> <p>and </p> <pre><code>error: no type named ‘type’ in ‘struct boost::enable_if&lt;boost::is_floating_point&lt;int&gt;, int&gt;’ </code></pre> <p>This indicates that I can't have different implementations for different types, at least not using boost's enable_if, is this correct?</p> <p>If so, how do I do this? I know that template specialization would be a way to go, but I would like to avoid duplicating too much code.</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