Search code examples
c++functionclassc++11inline

C++ inline initialize static function member


I want to implement a member function as follows:

void X() {}

class Foo
{
    static void(*Bar)() = X;
};

This does not compile:

error: 'constexpr' needed for in-class initialization of static data member 'void (* Foo::Bar)()' of non-integral type

I know this is not legal. I have to either initialize Bar outside of the class scope or make it "inline static". The problem is that the latter is a C++17 feature and I must do with C++11 (BCC32X limitations). So my question is: Is there a way to do this on the same line? Maybe making it const? I know we can do this(Source)...

class Foo
{
    static int const i = 42;
}

But can we apply it to functions somehow?

PD: I know there are infinite solutions to my question all over SO, but up until now all I've seen end up relying on later C++ features not available to me.


Solution

  • Since C++11 you can use constexpr to initialize static members of non-integral/enumeration types in the class declaration.

    As @paddy comments below, this makes Bar const so it would only be a viable solution if you don't plan to modify it, what you are not doing in the question's code.

    [Demo]

    #include <iostream>  // cout
    
    void X() {
        std::cout << "Blah\n";
    }
    
    struct Foo {
        static constexpr void(*Bar)() = X;
    };
    
    int main() {
        Foo::Bar();
    }