Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set static variable in function only once

Tags:

c++

eigen

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?

like image 614
user3726947 Avatar asked Aug 11 '18 22:08

user3726947


3 Answers

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.

like image 137
dfrib Avatar answered Oct 10 '22 01:10

dfrib


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;
}
like image 5
Guillaume Racicot Avatar answered Oct 10 '22 02:10

Guillaume Racicot


Something along these lines:

static Matrix3f P;
static bool dummy = (
  (P << Vector3f::UnitX(), Vector3f::UnitY(), Vector3f::Zero()),
  true);
like image 4
Igor Tandetnik Avatar answered Oct 10 '22 02:10

Igor Tandetnik