14#ifndef OR_TOOLS_SAT_MODEL_H_
15#define OR_TOOLS_SAT_MODEL_H_
26#include "absl/container/flat_hash_map.h"
27#include "absl/meta/type_traits.h"
28#include "ortools/base/logging.h"
29#include "ortools/base/macros.h"
30#include "ortools/base/map_util.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 return static_cast<const T*
>(
133 gtl::FindWithDefault(singletons_, gtl::FastTypeId<T>(),
nullptr));
139 template <
typename T>
141 return static_cast<T*
>(
142 gtl::FindWithDefault(singletons_, gtl::FastTypeId<T>(),
nullptr));
150 template <
typename T>
152 cleanup_list_.emplace_back(
new Delete<T>(t));
160 template <
typename T>
162 T* new_t = MyNew<T>(0);
172 template <
typename T>
174 const size_t type_id = gtl::FastTypeId<T>();
175 CHECK(!singletons_.contains(type_id));
176 singletons_[type_id] = non_owned_class;
179 const std::string&
Name()
const {
return name_; }
187 template <
typename T>
188 decltype(T(
static_cast<Model*
>(
nullptr)))* MyNew(
int) {
191 template <
typename T>
196 const std::string name_;
199 absl::flat_hash_map< size_t,
void*> singletons_;
201 struct DeleteInterface {
202 virtual ~DeleteInterface() =
default;
204 template <
typename T>
205 class Delete :
public DeleteInterface {
207 explicit Delete(T* t) : to_delete_(t) {}
208 ~Delete()
override =
default;
211 std::unique_ptr<T> to_delete_;
219 std::vector<std::unique_ptr<DeleteInterface>> cleanup_list_;
221 DISALLOW_COPY_AND_ASSIGN(
Model);
Class that owns everything related to a particular optimization model.
T * Create()
This returns a non-singleton object owned by the model and created with the T(Model* model) construct...
T Get(std::function< T(const Model &)> f) const
Similar to Add() but this is const.
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.
const std::string & Name() const
const T * Get() const
Likes GetOrCreate() but do not create the object if it is non-existing.
Model(std::string name)
When there is more than one model in an application, it makes sense to name them for debugging or log...
T * Mutable() const
Same as Get(), but returns a mutable version of the object.
void TakeOwnership(T *t)
Gives ownership of a pointer to this model.
T * GetOrCreate()
Returns an object of type T that is unique to this model (like a "local" singleton).