Two types using each other in C++
In my header file I have a function pointer and a struct:
typedef struct _CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* Resered;
} CONTINUE_STATE, *PCONTINUE_STATE;
--
typedef HRESULT (*CommandProc)(SOCKET client, char* command, char* response, CON开发者_开发问答TINUE_STATE* continueProc);
The problem is that CommandProc and CONTINUE_STATE both use each other. The function uses the struct as a argument and the struct uses the function as a member. This causes issues because whichever type is at the top of the header isn't able to find the type it uses.
Thanks in advance.
Edit: I know I can use void* for the func type in the struct then cast it later on but I'm wondering if there's a better way.
Forward declare the struct
:
struct _CONTINUE_STATE;
typedef struct _CONTINUE_STATE CONTINUE_STATE, *PCONTINUE_STATE;
typedef HRESULT (*CommandProc)(SOCKET client, char* command, char* response,
CONTINUE_STATE* continueProc);
struct _CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* Resered;
};
Firstly:
typedef struct _CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* Resered;
} CONTINUE_STATE, *PCONTINUE_STATE;
No need for typedefs, and you should not typedef pointers. So lets make that:
struct _CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* Resered;
};
Next, names begining with an underscorea and an uppercase letter are reserved, so:
struct CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* Resered;
};
And, if you really do need mutually referenced type names, which isn't obvious from your code, and isn't very commonly needed then:
struct CONTINUE_STATE {
DWORD CurrentCycle;
struct CommandProc * CommandFunc; // forward declaration
void* Resered;
};
Lastly, by convention type names in C++ are in mixed case, with uppercase being reserved for constants, so:
struct ContinueState {
DWORD CurrentCycle;
struct CommandProc * CommandFunc; // forward declaration
void* Resered;
};
Pretty simply, you can just forward declare the _CONTINUE_STATE
(a horrific and probably undefined name for a type, by the way) and still use it in the typedef. And you don't need to typedef structs like that in C++.
You have to use the pre-declaration.
struct CONTINUE_STATE;
typedef HRESULT (*CommandProc)(SOCKET client, char* command, char* response, CONTINUE_STATE* continueProc);
typedef struct _CONTINUE_STATE {
DWORD CurrentCycle;
CommandProc* CommandFunc;
void* Resered;
} CONTINUE_STATE, *PCONTINUE_STATE;
精彩评论