1

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.

paddy
  • 60,864
  • 6
  • 61
  • 103
Ricardo
  • 337
  • 5
  • 16

1 Answers1

5

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();
}
rturrado
  • 7,699
  • 6
  • 42
  • 62
  • 2
    Unless the OP confirms that they never intend to modify function pointer at runtime, we can't assume that this is a viable solution. When `Bar` is a constexpr it cannot be modified at runtime, whereas a static value can. – paddy Feb 22 '22 at 20:44
  • 1
    @paddy That's right. This makes `Bar` const. And `Bar` wasn't const in the original OP's code. – rturrado Feb 22 '22 at 20:46
  • 1
    I can make up with it being const as in truth X will never change. Thank you very much rturrado for your answer and @paddy for your edit. – Ricardo Feb 22 '22 at 21:26