Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call static method in global scope

Tags:

c++

static

I have a class that store a collection of types. This types are registered by other class using a static method from the first class.

Here is some code :

in file classA.h

class A {
    static void RegisterType(std::string name, bool (*checkType)(Json::Value toCheck));
}

In file classB.h

class B {
    static bool CheckType(Json::Value toCheck);
}

In file classB.cpp

// In global scope
A::RegisterType("B", &B::CheckType);

When I do this in classB.cpp my compiler (Visual Studio 2010) think I want to redeclare the A::RegisterType() function.

I try to change return type of A::RegisterType() from void to bool. And then assign the returned value to a variable in classB.cpp :

// In global scope
bool tmp = A::RegisterType("B", &B::CheckType);

This way it does work, but I add a variable in global scope and I don't want to.

How can I call A::RegisterType() from global scope without assign his result to a variable ?

Another question is how can I register the "B" type from classB.cpp ?

like image 504
AMDG Avatar asked Jun 01 '26 23:06

AMDG


1 Answers

There are no "freestanding" function calls in C++ : you can call RegisterType() from another static method (e.g., from main())

A workaround is to mimic a static constructor :

struct StaticInit
{
    StaticInit() 
    {
        A::RegisterType("B", &B::CheckType); 
    }
};

class B
{
    // ...
    static StaticInit si; // Will force the static initialization
};
like image 59
quantdev Avatar answered Jun 05 '26 02:06

quantdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!