Function pointer error

I have 2 functions,
callFunc is a class member
testFunc isn't a class member
I can bind a function pointer to testFunc but I cannot do that for callFunc (line 21, 22 in FreeClass.cpp)
How I can bind a function pointer to a function in a class?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//common.h
#ifndef COMMON_H
#define COMMON_H

#ifdef __cplusplus
extern "C" {
#endif
    typedef void(*CallFunction_t)(int id, void* ptr);
    typedef void(*TestFunction_t)(int id, void* ptr);
    typedef struct
    {
        CallFunction_t callFunc;
        TestFunction_t testFunc;
        void* ptr;                   
    } CommonStruct_t;

#ifdef __cplusplus
}
#endif
#endif   //COMMON_H 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//FreeClass.cpp
#include "FreeClass.h"
#include "common.h"
void testFunc(int id, void* ptr)
{
    switch (id)
    {
    case 0:
        ((FreeClass*)ptr)->say_hello();
        break;
    case 1:
        ((FreeClass*)ptr)->say_goodbye();
        break;
    default:
        break;
    }
}
FreeClass::FreeClass(void)
{
    CommonStruct_t comStr;
    comStr.callFunc = callFunc;//Error : a value of type "void (FreeClass::*)(int id, void *ptr)" cannot be assigned to an entity of type "CallFunction_t"
    comStr.testFunc = testFunc; // OK
    comStr.ptr = this;
}

FreeClass::~FreeClass(void)
{
}

void FreeClass::callFunc(int id, void * ptr)
{
    switch (id)
    {
    case 0:
        ((FreeClass*)ptr)->say_hello();
        break;
    case 1:
        ((FreeClass*)ptr)->say_goodbye();
        break;
    default:
        break;
    }
}

void FreeClass::say_hello()
{
    std::cout << "Hello\n";
}

void FreeClass::say_goodbye()
{
    std::cout << "GoodBye\n";
}
Last edited on
Make callFunc(...) static:
1
2
3
4
5
6
class FreeClass
{
  ...
  static void callFunc(int id, void * ptr);
  ...
};
The issue is that you can't call member function without object:
1
2
FreeClass fc;
fc.callFunc( 42, nullptr );

That is, the above member function call is like there were:
1
2
3
4
void callFunc(FreeClass* this, int id, void* ptr);

FreeClass fc;
callFunc( &fc, 42, nullptr );


Static member functions are like standalone functions, except that they have different access rules.
Have considered std::function?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <functional>
  
struct Math {
    long factorial(long term) {
        if (term < 2)
            return 1;
        return factorial(term - 1) * term;
    }
};

int main() {
    Math m;
    std::function<long(long)> factorial = std::bind(&Math::factorial, m, std::placeholders::_1);

    factorial(3); // call m.factorial(3);
}

See: https://en.cppreference.com/w/cpp/utility/functional/function
Last edited on
Topic archived. No new replies allowed.