| 1 | /* This file is part of the FaCT++ DL reasoner |
| 2 | Copyright (C) 2010-2015 Dmitry Tsarkov and The University of Manchester |
| 3 | Copyright (C) 2015-2017 Dmitry Tsarkov |
| 4 | |
| 5 | This library is free software; you can redistribute it and/or |
| 6 | modify it under the terms of the GNU Lesser General Public |
| 7 | License as published by the Free Software Foundation; either |
| 8 | version 2.1 of the License, or (at your option) any later version. |
| 9 | |
| 10 | This library is distributed in the hope that it will be useful, |
| 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 | Lesser General Public License for more details. |
| 14 | |
| 15 | You should have received a copy of the GNU Lesser General Public |
| 16 | License along with this library; if not, write to the Free Software |
| 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 18 | */ |
| 19 | |
| 20 | #ifndef THEADTAILCACHE_H |
| 21 | #define THEADTAILCACHE_H |
| 22 | |
| 23 | #include <map> |
| 24 | |
| 25 | /// Template class for the cache element. Assumes that new elements of a HEADTYPE |
| 26 | /// are constructed using a single argument of a TAILTYPE. Uniqueness of a tails |
| 27 | /// leads to the uniqueness of a constructed object |
| 28 | template <typename HeadType, typename TailType> |
| 29 | class THeadTailCache |
| 30 | { |
| 31 | protected: // types |
| 32 | /// auxiliary map |
| 33 | typedef std::map<const TailType*,HeadType*> CacheMap; |
| 34 | |
| 35 | protected: // members |
| 36 | /// map tail into an object head(tail) |
| 37 | CacheMap Map; |
| 38 | |
| 39 | protected: // methods |
| 40 | /// the way to create an object by a given tail |
| 41 | virtual HeadType* build ( TailType* ) = 0; |
| 42 | |
| 43 | public: // interface |
| 44 | /// empty c'tor |
| 45 | THeadTailCache() = default; |
| 46 | /// empty d'tor |
| 47 | virtual ~THeadTailCache() = default; |
| 48 | |
| 49 | /// get an object corresponding to Head.Tail |
| 50 | HeadType* get ( TailType* tail ) |
| 51 | { |
| 52 | // try to find cached dep-set |
| 53 | auto p = Map.find(tail); |
| 54 | if ( p != Map.end() ) |
| 55 | return p->second; |
| 56 | |
| 57 | // no cached entry -- create a new one and cache it |
| 58 | HeadType* concat = build(tail); |
| 59 | Map[tail] = concat; |
| 60 | return concat; |
| 61 | } |
| 62 | }; // THeadTailCache |
| 63 | |
| 64 | |
| 65 | #endif |