Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const Static Function Pointer in Class ~ How to initialize it?

Tags:

c++

I have this small piece of code:

int add(int x, int y)
{
    return x + y;
}

class A
{
public:
    const static int (*FP)(int, int) = &add;
};

int main()
{
    int x = 3;
    int y = 2;
    int z = A::FP(x, y);
    return 0;
}

Under VS2012 this generates the following error: error C2864: 'A::FP' : only static const integral data members can be initialized within a class.

Is there something I am not seeing? Or is it plainly not possible for some reason?

Christian


2 Answers

Initialize outside of the class definition, using a typedef to make the constness possible:

typedef int (*func_t)(int, int);

class A
{
public:
    const static func_t FP;
};

const func_t A::FP = &add;

Without the typedef the declaration:

const static int (*FP)(int, int) = &add;

is a static function pointer named FP with a return type of const int, not a const function pointer. When compiled with warnling level /W4 the following diagnostic is emitted:

warning C4180: qualifier applied to function type has no meaning; ignored

this was not immediately apparent due to the ordering of the declaration, const static int instead of static const int.

like image 200
hmjd Avatar answered Apr 16 '26 11:04

hmjd


In C++03. In class initialization of non-intgeral or enum data-types is not allowed.

class A
{
public:
    typedef int (*FP_ptr)(int, int);
    const static FP_ptr FP;
};

const A::FP_ptr 
A::FP = &add;

C++11

class A
{
public:
    constexpr static int (*FP)(int, int) = &add;
};
like image 43
stardust Avatar answered Apr 16 '26 09:04

stardust



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!