First, i believe you originally mean to return
StaticVector<N>
Instead of always a specialization with N==3 . So, what you want to do is writing it like this:
template <unsigned int N>
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<N>.
static StaticVector create3dVec(double x1, double x2, double x2) {
// create a new, empty, StaticVector
return StaticVector();
}
};
If you really want to always return a 3dVector, you would probably want to restrict it to N==3, so that for example StaticVector<4>::create3dVec
doesn't work. You can do that using the technique described here.
If you want to have a function like createVec
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 variadic templates for this purpose. Anyway,consider using something like this:
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:
static StaticVector createVec(double (&values)[N]) {
// create a new, empty, StaticVector, initializing it
// with the given array of N values.
return StaticVector();
}
You could use it with
double values[3] = {1, 2, 3};
StaticVector<3> v = StaticVector<3>::createVec(values);
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:
// oops, values is a null pointer!
StaticVector<3> v = StaticVector<3>::createVec(values);
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 :)