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 void 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 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 // TODO, detect availability std::is_trivially_copyable / workaround
150 // std::is_trivially_copyable is not available before GCC 5.
153 // The only types we can portably store directly in the Task are the
154 // trivially copyable ones (we can memcpy) which are small enough to fit:
155 return std::is_trivially_copyable<F>::value &&
156 sizeof(F) <= sizeof(bits::any_callback);
162 /** Type-erased run-once task
164 * * Like std::function but callable only once.
165 * However, it works with move-only types.
167 * * Like std::packaged_task<> but without the shared state.
169 template<class R, class... Args>
170 class Task<R(Args...)> {
173 typedef bits::TaskErasure TaskErasure;
174 struct TaskErasureVtable {
175 // Call (and possibly destroy) the function:
176 R (*call)(TaskErasure&, Args...);
177 // Destroy the function:
178 void (*destroy)(TaskErasure&);
182 const TaskErasureVtable* vtable_ = nullptr;
186 Task(std::nullptr_t) {}
189 if (vtable_ && vtable_->destroy)
190 vtable_->destroy(code_);
193 Task(Task const&) = delete;
194 Task& operator=(Task const&) = delete;
198 std::memcpy(&code_, &that.code_, sizeof(code_));
199 vtable_ = that.vtable_;
200 that.vtable_ = nullptr;
202 Task& operator=(Task&& that)
204 if (vtable_ && vtable_->destroy)
205 vtable_->destroy(code_);
206 std::memcpy(&code_, &that.code_, sizeof(code_));
207 vtable_ = that.vtable_;
208 that.vtable_ = nullptr;
213 typename = typename std::enable_if<bits::isUsableDirectlyInTask<F>()>::type>
216 const static TaskErasureVtable vtable {
218 [](TaskErasure& erasure, Args... args) -> R {
219 // We need to wrap F un a union because F might not have a default
220 // constructor: this is especially the case for lambdas.
226 if (!std::is_empty<F>::value)
227 // AFAIU, this is safe as per [basic.types]:
228 std::memcpy(&code.code, erasure.any.data(), sizeof(code.code));
229 code.code(std::forward<Args>(args)...);
234 if (!std::is_empty<F>::value)
235 std::memcpy(code_.any.data(), &code, sizeof(code));
240 typename = typename std::enable_if<!bits::isUsableDirectlyInTask<F>()>::type>
243 const static TaskErasureVtable vtable {
245 [](TaskErasure& erasure, Args... args) -> R {
246 // Delete F when we go out of scope:
247 std::unique_ptr<F> code(static_cast<F*>(erasure.ptr));
248 (*code)(std::forward<Args>(args)...);
251 [](TaskErasure& erasure) {
252 F* code = static_cast<F*>(erasure.ptr);
256 code_.ptr = new F(std::move(code));
261 Task(std::reference_wrapper<F> code)
263 const static TaskErasureVtable vtable {
265 [](TaskErasure& erasure, Args... args) -> R {
266 F* code = static_cast<F*>(erasure.ptr);
267 (*code)(std::forward<Args>(args)...);
272 code.code_.ptr = code.get();
276 // TODO, Task(funcptr)
277 // TODO, Task(funcptr, data)
278 // TODO, Task(method, object)
279 // TODO, Task(stateless lambda)
281 operator bool() const { return vtable_ != nullptr; }
282 bool operator!() const { return vtable_ == nullptr; }
284 R operator()(Args... args)
287 throw std::bad_function_call();
288 const TaskErasureVtable* vtable = vtable_;
290 return vtable->call(code_, std::forward<Args>(args)...);
294 template<class F, class... Args>
298 std::tuple<Args...> args_;
299 typedef decltype(simgrid::xbt::apply(std::move(code_), std::move(args_))) result_type;
301 TaskImpl(F code, std::tuple<Args...> args) :
302 code_(std::move(code)),
303 args_(std::move(args))
305 result_type operator()()
307 return simgrid::xbt::apply(std::move(code_), std::move(args_));
311 template<class F, class... Args>
312 auto makeTask(F code, Args... args)
313 -> Task< decltype(code(std::move(args)...))() >
315 TaskImpl<F, Args...> task(std::move(code), std::make_tuple(std::move(args)...));
316 return std::move(task);