#ifndef MT1Q5A_H #define MT1Q5A_H ///////////////////////////////////////////// // MT1Q5a.h - Scope Interface and Factory #include #include #include struct IScope { using Name = std::string; using Type = std::string; using Complexity = size_t; virtual ~IScope() {} static IScope* Create(); static IScope* Create(const Name& name, const Type& type, Complexity comp); virtual Name& name() = 0; virtual Type& type() = 0; virtual Complexity& complexity() = 0; virtual bool match(const IScope* pS) = 0; virtual bool operator<(const IScope* pS) = 0; }; class Scope : public IScope { public: Scope(Name n, Type t, Complexity c) : _name(n), _type(t), _complexity(c) {} Scope() {} Name& name() { return _name; } Type& type() { return _type; } Complexity& complexity() { return _complexity; } bool match(const IScope* pS); bool operator<(const IScope* pS); private: Name _name = "unknown"; Type _type = "unknown"; Complexity _complexity = 0; }; inline IScope* IScope::Create() { return new Scope; } IScope* IScope::Create(const Name& name, const Type& type, Complexity comp) { return new Scope(name, type, comp); } inline bool Scope::match(const IScope* pS) { IScope* pCS = const_cast(pS); Scope::Complexity complexityTolerance = 1; bool complexityMatch = (this->complexity() < pCS->complexity() + complexityTolerance) && (this->complexity() > pCS->complexity() - complexityTolerance); return complexityMatch; } inline bool Scope::operator<(const IScope* pS) { IScope* pCS = const_cast(pS); return this->complexity() > pCS->complexity(); } /////////////////////////////////////////////////////////// // ScopeCollection template // bool compare(const Scope* pS1, const Scope* pS2) struct IScopeCollection { using Scopes = std::vector; using iterator = Scopes::iterator; static IScopeCollection* create(); virtual ~IScopeCollection() {} virtual iterator begin() = 0; virtual iterator end() = 0; virtual IScopeCollection& add(IScope* pS) = 0; virtual void sort(Compare& compare) = 0; }; template class ScopeCollection : public IScopeCollection { public: ScopeCollection() {} ScopeCollection(std::initializer_list lsp) { for (auto pScope : lsp) _scopes.push_back(pScope); } ScopeCollection& add(IScope* pS) { _scopes.push_back(pS); return *this; } typename IScopeCollection::iterator begin() { return _scopes.begin(); } typename IScopeCollection::iterator end() { return _scopes.end(); } void sort(Compare& compare) { std::sort( _scopes.begin(), _scopes.end(), compare); } private: std::vector _scopes; }; template IScopeCollection* IScopeCollection::create() { return new ScopeCollection(); } #endif