14 #ifndef OR_TOOLS_SAT_MODEL_H_
15 #define OR_TOOLS_SAT_MODEL_H_
27 #include "absl/container/flat_hash_map.h"
28 #include "absl/meta/type_traits.h"
29 #include "ortools/base/logging.h"
30 #include "ortools/base/macros.h"
31 #include "ortools/base/typeid.h"
49 for (
int i = cleanup_list_.size() - 1; i >= 0; --i) {
50 cleanup_list_[i].reset();
58 explicit Model(std::string name) : name_(name) {}
91 T
Get(std::function<T(
const Model&)> f)
const {
109 template <
typename T>
111 const size_t type_id = gtl::FastTypeId<T>();
112 auto find = singletons_.find(type_id);
113 if (find != singletons_.end()) {
114 return static_cast<T*
>(find->second);
119 T* new_t = MyNew<T>(0);
120 singletons_[type_id] = new_t;
130 template <
typename T>
132 const auto& it = singletons_.find(gtl::FastTypeId<T>());
133 return it != singletons_.end() ?
static_cast<const T*
>(it->second)
140 template <
typename T>
142 const auto& it = singletons_.find(gtl::FastTypeId<T>());
143 return it != singletons_.end() ?
static_cast<T*
>(it->second) :
nullptr;
151 template <
typename T>
153 cleanup_list_.emplace_back(
new Delete<T>(t));
162 template <
typename T>
164 T* new_t = MyNew<T>(0);
174 template <
typename T>
176 const size_t type_id = gtl::FastTypeId<T>();
177 CHECK(!singletons_.contains(type_id));
178 singletons_[type_id] = non_owned_class;
181 const std::string&
Name()
const {
return name_; }
189 template <
typename T>
190 decltype(T(
static_cast<Model*
>(
nullptr)))* MyNew(
int) {
193 template <
typename T>
198 const std::string name_;
201 absl::flat_hash_map< size_t,
void*> singletons_;
203 struct DeleteInterface {
204 virtual ~DeleteInterface() =
default;
206 template <
typename T>
207 class Delete :
public DeleteInterface {
209 explicit Delete(T* t) : to_delete_(t) {}
210 ~Delete()
override =
default;
213 std::unique_ptr<T> to_delete_;
221 std::vector<std::unique_ptr<DeleteInterface>> cleanup_list_;
223 DISALLOW_COPY_AND_ASSIGN(
Model);
Class that owns everything related to a particular optimization model.
const std::string & Name() const
T Get(std::function< T(const Model &)> f) const
Similar to Add() but this is const.
T * Create()
This returns a non-singleton object owned by the model and created with the T(Model* model) construct...
const T * Get() const
Likes GetOrCreate() but do not create the object if it is non-existing.
T * TakeOwnership(T *t)
Gives ownership of a pointer to this model.
T Add(std::function< T(Model *)> f)
This makes it possible to have a nicer API on the client side, and it allows both of these forms:
void Register(T *non_owned_class)
Register a non-owned class that will be "singleton" in the model.
T * GetOrCreate()
Returns an object of type T that is unique to this model (like a "local" singleton).
T * Mutable() const
Same as Get(), but returns a mutable version of the object.
Model(std::string name)
When there is more than one model in an application, it makes sense to name them for debugging or log...