Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"How can I declare and define in this class"</p> <p>In what class? You've defined a class template, not a class. You can't call a static function of a class template itself, you have to call a particular version of the static function that's part of a real class.</p> <p>So, do you want the template (and hence all instantiations of it) to have a function returning a StaticVector&lt;3&gt;, or do you want one particular instantiation of that template to have a function returning a StaticVector&lt;3&gt;?</p> <p>If the former:</p> <pre><code> template &lt;unsigned int N&gt; struct SV { int contents[N]; static SV&lt;3&gt; get3dVec(int x, int y, int z) { SV&lt;3&gt; v; v.contents[0] = x; v.contents[1] = y; v.contents[2] = z; return v; } }; int main() { SV&lt;3&gt; v = SV&lt;1&gt;::get3dVec(1,2,3); } </code></pre> <p>works for me.</p> <p>If the latter (you only want get3dVec to be a member of SV&lt;3&gt;, not of all SV&lt;whatever&gt;), then you want template specialisation:</p> <pre><code> template &lt;unsigned int N&gt; struct SV { int contents[N]; }; template&lt;&gt; struct SV&lt;3&gt; { int contents[3]; // must be re-declared in the specialization static SV&lt;3&gt; get3dVec(int x, int y, int z) { SV&lt;3&gt; v; v.contents[0] = x; v.contents[1] = y; v.contents[2] = z; return v; } }; int main() { SV&lt;3&gt; v = SV&lt;1&gt;::get3dVec(1,2,3); // compile error SV&lt;3&gt; v = SV&lt;3&gt;::get3dVec(1,2,3); // OK } </code></pre> <p>If for no other reason than to make the calling code look nicer by omitting the basically irrelevant template parameter, I agree with Iraimbilanja that normally a free function (in a namespace if you're writing for re-use) would make more sense for this example. </p> <p>C++ templates mean that you don't need static functions as much in C++ as you do in Java: if you want a "foo" function that does one thing for class Bar and another thing for class Baz, you can declare it as a function template with a template parameter that can be Bar or Baz (and which may or may not be inferred from function parameters), rather than making it a static function on each class. But if you do want it to be a static function, then you have to call it using a specific class, not just a template name.</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