Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing C++11 std::enable_if to enable member function if vector is specific length
    primarykey
    data
    text
    <p>I am writing a simple vector class and I would like to have some member functions that are only available in vectors of certain lengths (cross product for a 3 element vector for example). I stumbled across std::enable_if and it looks like it may be able to do what I want, but I don't seem to be able to get it working correctly.</p> <pre><code>#include &lt;iostream&gt; #include &lt;type_traits&gt; template&lt;typename T, unsigned int L&gt; class Vector { private: T data[L]; public: Vector&lt;T,L&gt;(void) { for(unsigned int i = 0; i &lt; L; i++) { data[i] = 0; } } T operator()(const unsigned int i) const { return data[i]; } T&amp; operator()(const unsigned int i) { return data[i]; } Vector&lt;typename std::enable_if&lt;L==3, T&gt;::type, L&gt; cross(const Vector&lt;T,L&gt;&amp; vec2) const { Vector&lt;T,L&gt; result; result(0) = (*this)(1) * vec2(2) - (*this)(2) * vec2(1); result(1) = (*this)(2) * vec2(0) - (*this)(0) * vec2(2); result(2) = (*this)(0) * vec2(1) - (*this)(1) * vec2(0); return result; } }; int main(void) { Vector&lt;double,3&gt; v1; Vector&lt;double,3&gt; v2; Vector&lt;double,3&gt; v3; //Vector&lt;double,4&gt; v4; v1(0) = 1; v1(1) = 2; v1(2) = 3; v2(0) = 4; v2(1) = 5; v2(2) = 6; v3 = v1.cross(v2); std::cout &lt;&lt; v3(0) &lt;&lt; std::endl; std::cout &lt;&lt; v3(1) &lt;&lt; std::endl; std::cout &lt;&lt; v3(2) &lt;&lt; std::endl; return 0; } </code></pre> <p>The code above compiles and runs correctly, however if I uncomment the declaration of <code>Vector&lt;double,4&gt; v4</code> I get the following error at compilation:</p> <pre><code>vec.cpp: In instantiation of ‘class Vector&lt;double, 4u&gt;’: vec.cpp:46:22: required from here vec.cpp:29:59: error: no type named ‘type’ in ‘struct std::enable_if&lt;false, double&gt;’ </code></pre> <p>Is someone able to point out where I am going wrong?</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.
 

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