Reputation: 531
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?
Upvotes: 6
Views: 540
Reputation: 41800
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;
}
Upvotes: 5
Reputation: 73206
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
.
Upvotes: 8
Reputation: 52611
Something along these lines:
static Matrix3f P;
static bool dummy = (
(P << Vector3f::UnitX(), Vector3f::UnitY(), Vector3f::Zero()),
true);
Upvotes: 4