heczaco heczaco - 1 month ago 4x
C++ Question

Having includes just in cpp file

I'd like to have includes just in .cpp files, as I'm working in a project with lots of classes which will have to interact with each other, and I feel it's a bit better since you don't have to worry for what you have already included or not, I just don't know well how to do it;
here's an example:

#include "UnitConverter.hpp"
#include <string>
//extern namespace std;
//extern class std::string;
//extern class UnitConverter;
//extern enum UnitConverter::UnitTypes;
//extern enum UnitConverter::UnitSystem;
//extern enum UnitConverter::ScalingType;

class AnalogOutput{

std::string name;
UnitConverter::UnitTypes unit_type;
UnitConverter::UnitSystem unit_system;
UnitConverter::ScalingType scaling_type;

how would I declare the namespaces, classes and enum types so that compiles without the includes in the hpp file but in the cpp file?


std::string will make it difficult for you, as it is a typedef to a template... Better do not worry about that one - it is extremely unlikely that you would get circular includes with the system headers...

For your project's classes, you will have to declare them exactly as they have been declared in their corresponding header:

// Example.h
namespace Dummy
    class Example { /* ... */ };

And then to avoid includes:

// Test.h
namespace Dummy
    class Example; // just the bare name!

But be aware that this way, you get incomplete types, and you cannot use them directly. You can use pointers or references to them, but the following composition won't work:

// Test.h
/* ... */
class Test
    Dummy::Example ex;    // type is incomplete!
    Dummy::Example& ex_r; // reference is OK
    Dummy::Example* ex_p; // pointer, too

    inline void foo()
        // type incomplete; you cannot do this here:
        // needs to be done in cpp file where Example.h is included instead