1 /* Copyright (c) 2015-2016. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
7 #ifndef XBT_FUNCTIONAL_HPP
8 #define XBT_FUNCTIONAL_HPP
20 #include <type_traits>
24 #include <xbt/sysdep.h>
25 #include <xbt/utility.hpp>
34 std::shared_ptr<const std::vector<std::string>> args_;
36 MainFunction(F code, std::vector<std::string> args) :
37 code_(std::move(code)),
38 args_(std::make_shared<const std::vector<std::string>>(std::move(args)))
40 int operator()() const
42 const int argc = args_->size();
43 std::vector<std::string> args = *args_;
44 std::unique_ptr<char*[]> argv(new char*[argc + 1]);
45 for (int i = 0; i != argc; ++i)
46 argv[i] = args[i].empty() ? const_cast<char*>(""): &args[i].front();
48 return code_(argc, argv.get());
52 template<class F> inline
53 std::function<void()> wrapMain(F code, std::vector<std::string> args)
55 return MainFunction<F>(std::move(code), std::move(args));
58 template<class F> inline
59 std::function<void()> wrapMain(F code, int argc, const char*const argv[])
61 std::vector<std::string> args(argv, argv + argc);
62 return MainFunction<F>(std::move(code), std::move(args));
66 template <class F, class Tuple, std::size_t... I>
67 constexpr auto apply(F&& f, Tuple&& t, simgrid::xbt::index_sequence<I...>)
68 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...))
70 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
74 /** Call a functional object with the values in the given tuple (from C++17)
77 * int foo(int a, bool b);
79 * auto args = std::make_tuple(1, false);
80 * int res = apply(foo, args);
83 template <class F, class Tuple>
84 constexpr auto apply(F&& f, Tuple&& t)
85 -> decltype(simgrid::xbt::bits::apply(
87 std::forward<Tuple>(t),
88 simgrid::xbt::make_index_sequence<
89 std::tuple_size<typename std::decay<Tuple>::type>::value
92 return simgrid::xbt::bits::apply(
94 std::forward<Tuple>(t),
95 simgrid::xbt::make_index_sequence<
96 std::tuple_size<typename std::decay<Tuple>::type>::value
100 template<class T> class Task;
104 // Compute the maximum size taken by any of the given types:
105 template <class... T> struct max_size;
107 struct max_size<> : public std::integral_constant<std::size_t, 0> {};
109 struct max_size<T> : public std::integral_constant<std::size_t, sizeof(T)> {};
110 template <class T, class... U>
111 struct max_size<T, U...> : public std::integral_constant<std::size_t,
112 (sizeof(T) > max_size<U...>::value) ? sizeof(T) : max_size<U...>::value
117 // What we can store in a Task:
118 typedef void* ptr_callback;
119 struct funcptr_callback {
120 // Placeholder for any function pointer:
124 struct member_funcptr_callback {
125 // Placeholder for any pointer to member function:
126 void (whatever::* callback)();
129 constexpr std::size_t any_size = max_size<
132 member_funcptr_callback
134 typedef std::array<char, any_size> any_callback;
136 // Union of what we can store in a Task:
139 funcptr_callback funcptr;
140 member_funcptr_callback member_funcptr;
144 // Can we copy F in Task (or do we have to use the heap)?
146 constexpr bool isUsableDirectlyInTask()
148 // The only types we can portably store directly in the Task are the
149 // trivially copyable ones (we can memcpy) which are small enough to fit:
150 return std::is_trivially_copyable<F>::value &&
151 sizeof(F) <= sizeof(bits::any_callback);
156 /** Type-erased run-once task
158 * * Like std::function but callable only once.
159 * However, it works with move-only types.
161 * * Like std::packaged_task<> but without the shared state.
163 template<class R, class... Args>
164 class Task<R(Args...)> {
167 typedef bits::TaskErasure TaskErasure;
168 struct TaskErasureVtable {
169 // Call (and possibly destroy) the function:
170 R (*call)(TaskErasure&, Args...);
171 // Destroy the function:
172 void (*destroy)(TaskErasure&);
176 const TaskErasureVtable* vtable_ = nullptr;
180 Task(std::nullptr_t) {}
183 if (vtable_ && vtable_->destroy)
184 vtable_->destroy(code_);
187 Task(Task const&) = delete;
188 Task& operator=(Task const&) = delete;
192 std::memcpy(&code_, &that.code_, sizeof(code_));
193 vtable_ = that.vtable_;
194 that.vtable_ = nullptr;
196 Task& operator=(Task&& that)
198 if (vtable_ && vtable_->destroy)
199 vtable_->destroy(code_);
200 std::memcpy(&code_, &that.code_, sizeof(code_));
201 vtable_ = that.vtable_;
202 that.vtable_ = nullptr;
207 typename = typename std::enable_if<bits::isUsableDirectlyInTask<F>()>::type>
210 const static TaskErasureVtable vtable {
212 [](TaskErasure& erasure, Args... args) -> R {
213 // We need to wrap F un a union because F might not have a default
214 // constructor: this is especially the case for lambdas.
220 if (!std::is_empty<F>::value)
221 // AFAIU, this is safe as per [basic.types]:
222 std::memcpy(&code.code, erasure.any.data(), sizeof(code.code));
223 code.code(std::forward<Args>(args)...);
228 if (!std::is_empty<F>::value)
229 std::memcpy(code_.any.data(), &code, sizeof(code));
234 typename = typename std::enable_if<!bits::isUsableDirectlyInTask<F>()>::type>
237 const static TaskErasureVtable vtable {
239 [](TaskErasure& erasure, Args... args) -> R {
240 // Delete F when we go out of scope:
241 std::unique_ptr<F> code(static_cast<F*>(erasure.ptr));
242 (*code)(std::forward<Args>(args)...);
245 [](TaskErasure& erasure) {
246 F* code = static_cast<F*>(erasure.ptr);
250 code_.ptr = new F(std::move(code));
255 Task(std::reference_wrapper<F> code)
257 const static TaskErasureVtable vtable {
259 [](TaskErasure& erasure, Args... args) -> R {
260 F* code = static_cast<F*>(erasure.ptr);
261 (*code)(std::forward<Args>(args)...);
266 code.code_.ptr = code.get();
270 operator bool() const { return vtable_ != nullptr; }
271 bool operator!() const { return vtable_ == nullptr; }
273 R operator()(Args... args)
276 throw std::bad_function_call();
277 const TaskErasureVtable* vtable = vtable_;
279 return vtable->call(code_, std::forward<Args>(args)...);
283 template<class F, class... Args>
287 std::tuple<Args...> args_;
288 typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
290 TaskImpl(F code, std::tuple<Args...> args) :
291 code_(std::move(code)),
292 args_(std::move(args))
294 result_type operator()()
296 return simgrid::xbt::apply(std::move(code_), std::move(args_));
300 template<class F, class... Args>
301 auto makeTask(F code, Args... args)
302 -> Task< decltype(code(std::move(args)...))() >
304 TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
305 return std::move(task);