Debian Codegraph @

third_party/function2/Readme.md

raw
1
2 # fu2::function an improved drop-in replacement to std::function
3
4 ![](https://img.shields.io/badge/Version-4.0.0-0091EA.svg) ![](https://img.shields.io/badge/License-Boost-blue.svg) [![Build Status](https://travis-ci.org/Naios/function2.svg?branch=master)](https://travis-ci.org/Naios/function2) [![Build status](https://ci.appveyor.com/api/projects/status/1tl0vqpg8ndccats/branch/master?svg=true)](https://ci.appveyor.com/project/Naios/function2/branch/master)
5
6 Provides improved implementations of `std::function`:
7
8 - **copyable** `fu2::function`
9 - **move-only** `fu2::unique_function` (capable of holding move only types)
10 - **non-owning** `fu2::function_view` (capable of referencing callables in a non owning way)
11
12 that provide many benefits and improvements over `std::function`:
13
14 - [x] **const**, **volatile**, **reference** and **noexcept** correct (qualifiers are part of the `operator()` signature)
15 - [x] **convertible** to and from `std::function` as well as other callable types
16 - [x] **adaptable** through `fu2::function_base` (internal capacity, copyable and exception guarantees)
17 - [x] **overloadable** with an arbitrary count of signatures (`fu2::function<bool(int), bool(float)>`)
18 - [x] **full allocator support** in contrast to `std::function`, which doesn't provide support anymore
19 - [x] **covered** by many unit tests and continuous integration services (*GCC*, *Clang* and *MSVC*)
20 - [x] **header only**, just copy and include `function.hpp` in your project
21 - [x] **permissively licensed** under the **boost** license
22
23
24 ## Table of Contents
25
26 * **[Documentation](#documentation)**
27 * **[How to use](#how-to-use)**
28 * **[Constructing a function](#constructing-a-function)**
29 * **[Non copyable unique functions](#non-copyable-unique-functions)**
30 * **[Convertibility of functions](#convertibility-of-functions)**
31 * **[Adapt function2](#adapt-function2)**
32 * **[Performance and optimization](#performance-and-optimization)**
33 * **[Small functor optimization](#small-functor-optimization)**
34 * **[Compiler optimization](#compiler-optimization)**
35 * **[std::function vs fu2::function](#stdfunction-vs-fu2function)**
36 * **[Coverage and runtime checks](#coverage-and-runtime-checks)**
37 * **[Compatibility](#compatibility)**
38 * **[License](#licence)**
39 * **[Similar implementations](#similar-implementations)**
40
41 ## Documentation
42
43 ### How to use
44
45 **function2** is implemented in one header (`function.hpp`), no compilation is required.
46 Just copy the `function.hpp` header in your project and include it to start.
47 It's recommended to import the library as git submodule using CMake:
48
49 ```sh
50 # Shell:
51 git submodule add https://github.com/Naios/function2.git
52 ```
53
54 ```cmake
55 # CMake file:
56 add_subdirectory(function2)
57 # function2 provides an interface target which makes it's
58 # headers available to all projects using function2
59 target_link_libraries(my_project function2)
60 ```
61
62 Use `fu2::function` as a wrapper for copyable function wrappers and `fu2::unique_function` for move only types.
63 The standard implementation `std::function` and `fu2::function` are convertible to each other, see [the chapter convertibility of functions](#convertibility-of-functions) for details.
64
65 A function wrapper is declared as following:
66 ```c++
67 fu2::function<void(int, float) const>
68 // Return type ~^ ^ ^ ^
69 // Parameters ~~~~~|~~~~~| ^
70 // Qualifier ~~~~~~~~~~~~~~~~~~~|
71 ```
72
73 * **Return type**: The return type of the function to wrap.
74 * **Arguments**: The argument types of the function to wrap.
75 Any argument types are allowed.
76 * **Qualifiers**: There are several qualifiers allowed:
77 - **no qualifier** provides `ReturnType operator() (Args...)`
78 - Can be assigned from const and no const objects (*mutable lambdas* for example).
79 - **const** provides `ReturnType operator() (Args...) const`
80 - Requires that the assigned functor is const callable (won't work with *mutable lambdas*),
81 - **volatile** provides `ReturnType operator() (Args...) volatile`
82 - Can only be assigned from volatile qualified functors.
83 - **const volatile** provides `ReturnType operator() (Args...) const volatile`
84 - Same as const and volatile together.
85 - **r-value (one-shot) functions** `ReturnType operator() (Args...) &&`
86 - one-shot functions which are invalidated after the first call (can be mixed with `const`, `volatile` and `noexcept`). Can only wrap callable objects which call operator is also qualified as `&&` (r-value callable). Normal (*C*) functions are considered to be r-value callable by default.
87 - **noexcept functions** `ReturnType operator() (Args...) noexcept`
88 - such functions are guaranteed not to throw an exception (can be mixed with `const`, `volatile` and `&&`). Can only wrap functions or callable objects which call operator is also qualified as `noexcept`. Requires enabled C++17 compilation to work (support is detected automatically). Empty function calls to such a wrapped function will lead to a call to `std::abort` regardless the wrapper is configured to support exceptions or not (see [adapt function2](#adapt-function2)).
89 * **Multiple overloads**: The library is capable of providing multiple overloads:
90 ```cpp
91 fu2::function<int(std::vector<int> const&),
92 int(std::set<int> const&) const> fn = [] (auto const& container) {
93 return container.size());
94 };
95 ```
96
97 ### Constructing a function
98
99 `fu2::function` and `fu2::unique_function` (non copyable) are easy to use:
100
101 ```c++
102 fu2::function<void() const> fun = [] {
103 // ...
104 };
105
106 // fun provides void operator()() const now
107 fun();
108 ```
109
110 ### Non copyable unique functions
111
112 `fu2::unique_function` also works with non copyable functors/ lambdas.
113
114 ```c++
115 fu2::unique_function<bool() const> fun = [ptr = std::make_unique<bool>(true)] {
116 return *ptr;
117 };
118
119 // unique functions are move only
120 fu2::unique_function<bool() const> otherfun = std::move(fun):
121
122 otherfun();
123 ```
124
125
126 ### Non owning functions
127
128 A `fu2::function_view` can be used to create a non owning view on a persistent object. Note that the view is only valid as long as the object lives.
129
130 ```c++
131 auto callable = [ptr = std::make_unique<bool>(true)] {
132 return *ptr;
133 };
134
135 fu2::function_view<bool() const> view(callable);
136 ```
137
138 ### Convertibility of functions
139
140 `fu2::function`, `fu2::unique_function` and `std::function` are convertible to each other when:
141
142 - The return type and parameter type match.
143 - The functions are both volatile or not.
144 - The functions are const correct:
145 - `noconst = const`
146 - `const = const`
147 - `noconst = noconst`
148 - The functions are copyable correct when:
149 - `unique = unique`
150 - `unique = copyable`
151 - `copyable = copyable`
152 - The functions are reference correct when:
153 - `lvalue = lvalue`
154 - `lvalue = rvalue`
155 - `rvalue = rvalue`
156 - The functions are `noexcept` correct when:
157 - `callable = callable`
158 - `callable = noexcept callable `
159 - `noexcept callable = noexcept callable`
160
161 | Convertibility from \ to | fu2::function | fu2::unique_function | std::function |
162 | ------------------------ | ------------- | -------------------- | ------------- |
163 | fu2::function | Yes | Yes | Yes |
164 | fu2::unique_function | No | Yes | No |
165 | std::function | Yes | Yes | Yes |
166
167 ```c++
168 fu2::function<void()> fun = []{};
169 // OK
170 std::function<void()> std_fun = fun;
171 // OK
172 fu2::unique_function<void()> un_fun = fun;
173
174 // Error (non copyable -> copyable)
175 fun = un_fun;
176 // Error (non copyable -> copyable)
177 fun = un_fun;
178
179 ```
180
181 ### Adapt function2
182
183 function2 is adaptable through `fu2::function_base` which allows you to set:
184
185 - **IsOwning**: defines whether the function owns its contained object
186 - **Copyable:** defines if the function is copyable or not.
187 - **Capacity:** defines the internal capacity used for [sfo optimization](#small-functor-optimization):
188 ```cpp
189 struct my_capacity {
190 static constexpr std::size_t capacity = sizeof(my_type);
191 static constexpr std::size_t alignment = alignof(my_type);
192 };
193 ```
194 - **IsThrowing** defines if empty function calls throw an `fu2::bad_function_call` exception, otherwise `std::abort` is called.
195 - **HasStrongExceptGuarantee** defines whether the strong exception guarantees shall be met.
196 - **Signatures:** defines the signatures of the function.
197
198 The following code defines an owning function with a variadic signature which is copyable and sfo optimization is disabled:
199
200 ```c++
201 template<typename Signature>
202 using my_function = fu2::function_base<true, true, fu2::capacity_none, true, false, Signature>;
203 ```
204
205 The following code defines a non copyable function which just takes 1 argument, and has a huge capacity for internal sfo optimization. Also it must be called as r-value.
206
207 ```c++
208 template<typename Arg>
209 using my_consumer = fu2::function_base<true, false, fu2::capacity_fixed<100U>,
210 true, false, void(Arg)&&>;
211
212 // Example
213 my_consumer<int, float> consumer = [](int, float) { }
214 std::move(consumer)(44, 1.7363f);
215 ```
216
217 ## Performance and optimization
218
219 ### Small functor optimization
220
221 function2 uses small functor optimization like the most common `std::function` implementations which means it allocates a small internal capacity to evade heap allocation for small functors.
222
223 Smart heap allocation moves the inplace allocated functor automatically to the heap to speed up moving between objects.
224
225 It's possible to disable small functor optimization through setting the internal capacity to 0.
226
227
228 ## Coverage and runtime checks
229
230 Function2 is checked with unit tests and valgrind (for memory leaks), where the unit tests provide coverage for all possible template parameter assignments.
231
232 ## Compatibility
233
234 Tested with:
235
236 - Visual Studio 2017+ Update 3
237 - Clang 3.8+
238 - GCC 5.4+
239
240 Every compiler with modern C++14 support should work.
241 *function2* only depends on the standard library.
242
243 ## License
244 *function2* is licensed under the very permissive Boost 1.0 License.
245
246 ## Similar implementations
247
248 There are similar implementations of a function wrapper:
249
250 - [pmed/fixed_size_function](https://github.com/pmed/fixed_size_function)
251 - stdex::function - A multi-signature function implementation.
252 - multifunction - Example from [Boost.TypeErasure](http://www.boost.org/doc/html/boost_typeerasure/examples.html#boost_typeerasure.examples.multifunction), another multi-signature function.
253 - std::function - [Standard](http://en.cppreference.com/w/cpp/utility/functional/function).
254 - boost::function - The one from [Boost](http://www.boost.org/doc/libs/1_55_0/doc/html/function.html).
255 - func::function - From this [blog](http://probablydance.com/2013/01/13/a-faster-implementation-of-stdfunction/).
256 - generic::delegate - [Fast delegate in C++11](http://codereview.stackexchange.com/questions/14730/impossibly-fast-delegate-in-c11), also see [here](https://code.google.com/p/cpppractice/source/browse/trunk/).
257 - ssvu::FastFunc - Another Don Clugston's FastDelegate, as shown [here](https://groups.google.com/a/isocpp.org/forum/#!topic/std-discussion/QgvHF7YMi3o).
258 - [cxx_function::function](https://github.com/potswa/cxx_function) - By David Krauss
259
260 Also check out the amazing [**CxxFunctionBenchmark**](https://github.com/jamboree/CxxFunctionBenchmark) which compares several implementations.