C++, removing #include or #include in class header

后端 未结 12 1428
感情败类
感情败类 2021-01-03 06:37

I want to remove, if possible, the includes of both and from my class header file. Both string and vector are return types of functions declare

12条回答
  •  独厮守ぢ
    2021-01-03 07:07

    WARNING

    Expect that doing this will cause uproar.

    The language allows you to derive your own classes:

    // MyKludges.h
    #include 
    #include 
    class KludgeIntVector : public std::vector { 
      // ... 
    };
    class KludgeDoubleVector : public std::vector {
      // ...
    };
    
    class KludgeString : public std::string {
      // ...
    };
    

    Change your functions to return KludgeString and KludgeIntVector. Since these are no longer templates, you can forward declare them in your header files, and include MyKludges.h in your implementation files.

    Strictly speaking, derived classes do not inherit base class constructors, destructors, assignment operators, and friends. You will need to provide (trivial) implementations of any that you're using.


    // LotsOfFunctions.h
    // Look, no includes!  All forward declared!
    class KludgeString;
    // 10,000 functions that use neither strings nor vectors
    // ...
    void someFunction(KludgeString &);
    // ... 
    // Another 10,000 functions that use neither strings nor vectors
    
    // someFunction.cpp
    // Implement someFunction in its own compilation unit
    //  and  arrive on the next line
    #include "MyKludges.h"
    #include "LotsOfFunctions.h"
    void someFunction(KludgeString &k) { k.clear(); }
    

提交回复
热议问题