Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, i believe you originally mean to return</p> <pre><code>StaticVector&lt;N&gt; </code></pre> <p>Instead of always a specialization with N==3 . So, what you want to do is writing it like this:</p> <pre><code>template &lt;unsigned int N&gt; class StaticVector { public: // because of the injected class-name, we can refer to us using // StaticVector . That is, we don't need to name all template // parameters like StaticVector&lt;N&gt;. static StaticVector create3dVec(double x1, double x2, double x2) { // create a new, empty, StaticVector return StaticVector(); } }; </code></pre> <p>If you really want to always return a 3dVector, you would probably want to restrict it to N==3, so that for example <code>StaticVector&lt;4&gt;::create3dVec</code> doesn't work. You can do that using the technique described <a href="https://stackoverflow.com/questions/347096/how-can-i-get-a-specialized-template-to-use-the-unspecialized-version-of-a-member/347107#347107"><strong>here</strong></a>.</p> <p>If you want to have a function like <code>createVec</code> that works with any size, you probably want to replace the parameters with an array. You can do otherwise, but that's advanced and requires some macro tricks applied with boost::preprocessor. It's not worth it i think. The next C++ version will provide <em>variadic templates</em> for this purpose. Anyway,consider using something like this:</p> <p>I think it would only complicate this unnecessarily here. A quick solution is to use a boost::fusion::vector instead, putting it into the class template instead of the version above:</p> <pre><code>static StaticVector createVec(double (&amp;values)[N]) { // create a new, empty, StaticVector, initializing it // with the given array of N values. return StaticVector(); } </code></pre> <p>You could use it with</p> <pre><code>double values[3] = {1, 2, 3}; StaticVector&lt;3&gt; v = StaticVector&lt;3&gt;::createVec(values); </code></pre> <p>Note that it accepts an array by reference. You can't give it a pointer. That is because it matches the use of parameters: You couldn't provide less or more arguments for the other way too. It will also protect you from cases like this:</p> <pre><code>// oops, values is a null pointer! StaticVector&lt;3&gt; v = StaticVector&lt;3&gt;::createVec(values); </code></pre> <p>An array never can be a null pointer. Of course if you like, you can always change the array parameter to a pointer. It would just be my personal preference :)</p>
 

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