• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef FRUIT_LAMBDA_INVOKER_H
18 #define FRUIT_LAMBDA_INVOKER_H
19 
20 #include <fruit/impl/fruit-config.h>
21 #include <fruit/impl/injection_errors.h>
22 #include <fruit/impl/meta/errors.h>
23 #include <fruit/impl/meta/metaprogramming.h>
24 #include <fruit/impl/meta/signatures.h>
25 #include <fruit/impl/meta/wrappers.h>
26 
27 #include <cstddef>
28 #include <functional>
29 #include <type_traits>
30 
31 namespace fruit {
32 namespace impl {
33 
34 template <typename T>
35 struct SafeAlignmentOf {
36   constexpr static const std::size_t value = alignof(T);
37 };
38 
39 template <typename T, typename... Args>
40 struct SafeAlignmentOf<T(Args...)> {
41   constexpr static const std::size_t value = alignof(int);
42 };
43 
44 class LambdaInvoker {
45 public:
46   template <typename F, typename... Args>
47   FRUIT_ALWAYS_INLINE static auto invoke(Args&&... args)
48       -> decltype(std::declval<const F&>()(std::declval<Args>()...)) {
49     // We reinterpret-cast a char[] to avoid de-referencing nullptr, which would technically be
50     // undefined behavior (even though we would not access any data there anyway).
51     // Sharing this buffer for different types F would also be undefined behavior since we'd break
52     // strict aliasing between those types.
53     alignas(SafeAlignmentOf<F>::value) static char buf[1];
54 
55     FruitStaticAssert(fruit::impl::meta::IsEmpty(fruit::impl::meta::Type<F>));
56     FruitStaticAssert(fruit::impl::meta::IsTriviallyCopyable(fruit::impl::meta::Type<F>));
57     // Since `F' is empty, a valid value of type F is already stored at the beginning of buf.
58     F* f = reinterpret_cast<F*>((char*)buf);
59     return (*f)(std::forward<Args>(args)...);
60   }
61 };
62 
63 } // namespace impl
64 } // namespace fruit
65 
66 #endif // FRUIT_LAMBDA_INVOKER_H
67