Search code examples
c++includetypedefusingforward-declaration

How to correctly forward declare struct with "using XXX"?


There is a header file "api.h" that I have to use, and I can NOT modify it, but all names of the structs in it are too long and with less readability, also the naming style of them is not similar to my project.

e.g. in file "api.h":

#pragma once
struct AVERYVERYLONGLONGNAMEOFSTRUCT1 {
   ...
};
struct AVERYVERYLONGLONGNAMEOFSTRUCT2 {
   ...
};
...

So, I created another header "common.h", so as to re-name them.

File "common.hpp":

#pragma once
#include "api.h"
namespace MyProject {
using ContraDef_t = AVERYVERYLONGLONGNAMEOFSTRUCT1;
using AccountDef_t = AVERYVERYLONGLONGNAMEOFSTRUCT2;
};

But I want to include it merely in implemental file( *.cpp ), instead of other header files, because I want to speed up the compiling process. Suppose I declare a class in "myclass.hpp", and implement it in "myclass.cpp". I try to add a forward declaration of struct ContraDef_t into "myclass.hpp", as following:

#pragma once
namespace MyProject {
struct ContraDef_t;
class MyClass_t {
   MyClass_t( const ContraDef_t * );
   ...
};
};

Then in "myclass.cpp":

#include "common.hpp"
#include "myclass.hpp"
namespace MyProject {
MyClass_t::MyClass_t( const ContraDef_t * pcd ) {
   ...
};
};

Finally, I can NOT pass the compiling with "error: using typedef-name ‘using ContraDef_t = struct AVERYVERYLONGLONGNAMEOFSTRUCT1’ after ‘struct’..."

How should I do? Any help or hints will be much appreciated!


Solution

  • Put only the forward declarations in the header and include that header:

    // common.h
    // dont include api.h here !
    struct AVERYVERYLONGLONGNAMEOFSTRUCT1;
    using ContraDef_t = AVERYVERYLONGLONGNAMEOFSTRUCT1;
    
    // my_class.h
    #include "common.h"
    struct my_class{ 
        ContraDef_t* c;
    };
    
    // my_class.cpp
    #include "my_class.h"
    #include "api.h"
    // ...