Home > Enterprise >  How to make void(*)(...) as a struct member
How to make void(*)(...) as a struct member

Time:06-10

for a demo code

#include <iostream>
#include <map>
#include <vector>
using namespace std;

typedef struct Student
{
    public: 
        Student(){}
        ~Student(){}
        static void print(int a,int b){printf("age is a\n");}
}Student;

int main(){
    void (*p)(int, int) = &Student::print;

    vector<void(*)(int,int)> tt;
    tt.push_back(p);
    tt[0](1,1);

    return 0;
}

when I want to make the void(*)(int,int) as a struct member, like

struct void_func_st{
    void(*)(int,int) f;
    int a;
};

the code is wrong. I don't know whether the struct could be made actually as I'm not familiar with how the void(*)(...) works. Or I just didn't get the right way to make void(*)(...) as a struct member. Can anyone give some advice?

CodePudding user response:

It would be (as you do for local variable p in main)

void(*f)(int,int);

CodePudding user response:

Use std::function and forget about the confusing function pointer syntax:

struct void_func_st {
    std::function<void(int,int)>; f;
    int a;
};

Even better, introduce a nice alias for it:

using MyFunction = std::function<void(int,int)>;
  • Related