So I was wondering if it is possible to set a static variable inside a function scope only once. For example consider this function:
void projectPointIntoPlane(const Affine3f& plane2xy, Vector3f& p)
{
static Matrix3f P;
P << Vector3f::UnitX(), Vector3f::UnitY(), Vector3f::Zero();
p = plane2xy.inverse() * P * plane2xy * p;
}
I would like to set P only once and not at every function call, how can I achive this?
Instead of declaring P
and thereafter initializing it separately, you can initialize it in the declaration, using the finished()
method of CommaInitializer
:
static const Matrix3f P =
(Matrix3f() << Vector3f::UnitX(), Vector3f::UnitY(),
Vector3f::Zero()).finished();
With this approach, you can also declare P
as const
.
You could use a lambda that returns the right value. Since it's in the initialization expression, it's only called once:
void projectPointIntoPlane(const Affine3f& plane2xy, Vector3f& p)
{
static Matrix3f P = []{
Matrix3f P;
P << Vector3f::UnitX(), Vector3f::UnitY(), Vector3f::Zero();
return P;
}();
p = plane2xy.inverse() * P * plane2xy * p;
}
Something along these lines:
static Matrix3f P;
static bool dummy = (
(P << Vector3f::UnitX(), Vector3f::UnitY(), Vector3f::Zero()),
true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With