How to auto-include all headers in directory

前端 未结 10 3208
被撕碎了的回忆
被撕碎了的回忆 2021-02-20 12:32

I\'m going through exercises of a C++ book. For each exercise I want to minimize the boilerplate code I have to write. I\'ve set up my project a certain way but it doesn\'t seem

10条回答
  •  一向
    一向 (楼主)
    2021-02-20 12:51

    Why not using object mechanisms ?

    You can use an Exemplar strategy for this.

    class BaseExercise
    {
    public:
      static bool Add(BaseExercise* b) { Collection().push_back(b); return true; }
      static size_t Solve() {
        size_t nbErrors = 0;
        for(collections_type::const_iterator it = Collection().begin(), end = Collection().end(); it != end; ++it)
          nbErrors += it->solve();
        return nbErrors;
      }
    
      size_t solve() const
      {
        try {
          this->solveImpl();
          return 0;
        } catch(std::exception& e) {
          std::cout << mName << " - end - " << e.what() << std::endl;
          return 1;
        }
      }
    protected:
      explicit BaseExercise(const char* name): mName(name)
      {
      }
    private:
      typedef std::vector collection_type;
      static collection_type& Collection() { collection_type MCollection; return MCollection; }
    
      virtual void solveImpl() const = 0;
    
      const char* mName;
    }; // class BaseExercise
    
    template 
    class BaseExerciseT: public BaseExercise
    {
    protected:
      explicit BaseExerciseT(const char* b): BaseExercise(b) { 
        static bool MRegistered = BaseExercise::Add(this);
      }
    };
    

    Okay, that's the base.

    // Exercise007.h
    #include "baseExercise.h"
    
    class Exercise007: public BaseExerciseT
    {
    public:
      Exercise007(): BaseExerciseT("Exercise007") {}
    private:
      virtual void solveImpl() const { ... }
    };
    
    // Exercise007.cpp
    Exercise007 gExemplar007;
    

    And for main

    // main.cpp
    #include "baseExercise.h"
    
    int main(int argc, char* argv[])
    {
      size_t nbErrors = BaseExercise::Solve();
      if (nbErrors) std::cout << nbErrors << " errors" << std::endl;
      return nbErrors;
    }
    

    And here, you don't need any script ;)

提交回复
热议问题