set static variable in function only once

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



set static variable in function only once



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?





I was going to upvote....but then I noticed your rep was 0xff.....jk +1
– DarthRubik
Aug 12 at 0:19





not sure what you mean...
– user3726947
Aug 12 at 10:41





You had exactly 255 reputation before I upvoted
– DarthRubik
Aug 12 at 12:09




3 Answers
3



Instead of declaring P and thereafter initializing it separately, you can initialize it in the declaration, using the finished() method of CommaInitializer:


P


finished()


CommaInitializer


static const Matrix3f P =
(Matrix3f() << Vector3f::UnitX(), Vector3f::UnitY(),
Vector3f::Zero()).finished();



With this approach, you can also declare P as const.


P


const





to me this looks way cleaner than what igor or rakete propose, but it is not so general...
– user3726947
Aug 11 at 23:13






@user3726947 indeed, this would be the idiomatic Eigen approach. If I didn't know this was Eigen (and did not have access to the fit-for-purpose finished() method) and would need general solution, Igor Tandetnik's lambda is a good approach.
– dfri
Aug 11 at 23:18



finished()



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);





Or fold the initialization in the lambda and then return the object.
– Rakete1111
Aug 11 at 22:44






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered