Assigning functions to structure in array

56061c41419632a08b42acc18fbcec1d
0
jerlank 101 Apr 18, 2011 at 08:58

Hi, I am trying to do the following:

Save.h:

typedef struct foo
{
unsigned saveno;
void (*save_fn)(void);
} save_rec;

save_rec *pSaveRec;

class TSmartHost : public TForm
{

private:

void save_Data1(void);
void save_Data2(void);


public:
__fastcall TForm1(TComponent* Owner)
{
save_rec Save_Tab[2] =
{
{1, save_Data1(void) },
{2, save_Data2(void) }
};
}

};

so that I can do this in the main app:

Save_Record(int iRecVal)
for(int i=0;i<10;i++)
{
if(iRecVal==i)
{
pSaveRec=Save_Tab;
pSaveRec->save_fn();
}
}

I am not so hot in c++, and got this working in standard c, but for my new threaded project I need to do this in c++, but I am not having major success. Any help or ideas will be appreciated!

Thanks

Johan

1 Reply

Please log in or register to post a reply.

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 Apr 18, 2011 at 09:20

First, use

...[[i][/i]/code] tags to post code.

Secondly, this isn't possible. Your methods need a 'this' pointer, and save_fn is just a regular function. So save_Data1, which is a void (TSmartHost::*)() can't be converted to a void(*)().

You could try using std::tr1::function to store the function "pointer" and std::tr1::bind to bind the 'this' pointer, but I don't know whether they're available for the compiler you're using (Borland?).

[code]#include <functional>

struct save_rec
{
    unsigned saveno;
    std::tr1::function<void()> save_fn;
};

save_rec Save_Tab[2] =
{
    {1, std::tr1::bind(&save_Data1, this) },
    {2, std::tr1::bind(&save_Data2, this) }
};

But I suggest you start learning C++ and OOP, rather than using a C++ compiler to compile C code, which is what you’re doing know. I rarely need to use function pointers in C++.