2 / Copyright (c) 2003, 2004 Jaakko Jarvi
3 / Copyright (c) 2008 John Maddock
4 / Copyright (c) 2011, 2013 Jeremiah Willcock
5 / Copyright (c) 2014 Glen Fernandes
7 / Use, modification, and distribution is subject to the Boost Software
8 / License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
9 / http://www.boost.org/LICENSE_1_0.txt)
12 [section:enable_if enable_if]
22 [section Introduction]
24 The `enable_if` family of templates is a set of tools to allow
25 a function template or a class template specialization to
26 include or exclude itself from a set of matching functions or
27 specializations based on properties of its template arguments.
28 For example, one can define function templates that are only
29 enabled for, and thus only match, an arbitrary set of types
30 defined by a traits class. The `enable_if` templates can also
31 be applied to enable class template specializations.
32 Applications of `enable_if` are discussed in length in
33 [link REF1 \[1\]] and [link REF2 \[2\]].
35 [section Header <boost/core/enable_if.hpp>]
39 template <class Cond, class T = void> struct enable_if;
40 template <class Cond, class T = void> struct disable_if;
41 template <class Cond, class T> struct lazy_enable_if;
42 template <class Cond, class T> struct lazy_disable_if;
44 template <bool B, class T = void> struct enable_if_c;
45 template <bool B, class T = void> struct disable_if_c;
46 template <bool B, class T> struct lazy_enable_if_c;
47 template <bool B, class T> struct lazy_disable_if_c;
55 Sensible operation of template function overloading in C++
56 relies on the /SFINAE/ (substitution-failure-is-not-an-error)
57 principle [link REF3 \[3\]]: if an invalid argument or return
58 type is formed during the instantiation of a function template,
59 the instantiation is removed from the overload resolution set
60 instead of causing a compilation error. The following example,
61 taken from [link REF1 \[1\]], demonstrates why this is
65 int negate(int i) { return -i; }
68 typename F::result_type negate(const F& f) { return -f(); }
71 Suppose the compiler encounters the call `negate(1)`. The first
72 definition is obviously a better match, but the compiler must
73 nevertheless consider (and instantiate the prototypes) of both
74 definitions to find this out. Instantiating the latter
75 definition with `F` as `int` would result in:
78 int::result_type negate(const int&);
81 where the return type is invalid. If this were an error, adding
82 an unrelated function template (that was never called) could
83 break otherwise valid code. Due to the SFINAE principle the
84 above example is not, however, erroneous. The latter definition
85 of `negate` is simply removed from the overload resolution set.
87 The `enable_if` templates are tools for controlled creation of
88 the SFINAE conditions.
94 [section The enable_if templates]
96 The names of the `enable_if` templates have three parts: an
97 optional `lazy_` tag, either `enable_if` or `disable_if`, and
98 an optional `_c` tag. All eight combinations of these parts
99 are supported. The meaning of the `lazy_` tag is described
101 core.enable_if.using_enable_if.enable_if_lazy below]. The
102 second part of the name indicates whether a true condition
103 argument should enable or disable the current overload. The
104 third part of the name indicates whether the condition
105 argument is a `bool` value (`_c` suffix), or a type containing
106 a static `bool` constant named `value` (no suffix). The latter
107 version interoperates with Boost.MPL.
109 The definitions of `enable_if_c` and `enable_if` are as follows
110 (we use `enable_if` templates unqualified but they are in the
114 template <bool B, class T = void>
120 struct enable_if_c<false, T> {};
122 template <class Cond, class T = void>
123 struct enable_if : public enable_if_c<Cond::value, T> {};
126 An instantiation of the `enable_if_c` template with the
127 parameter `B` as `true` contains a member type `type`, defined
128 to be `T`. If `B` is `false`, no such member is defined. Thus
129 `enable_if_c<B, T>::type` is either a valid or an invalid type
130 expression, depending on the value of `B`. When valid,
131 `enable_if_c<B, T>::type` equals `T`. The `enable_if_c`
132 template can thus be used for controlling when functions are
133 considered for overload resolution and when they are not. For
134 example, the following function is defined for all arithmetic
135 types (according to the classification of the Boost
136 *type_traits* library):
140 typename enable_if_c<boost::is_arithmetic<T>::value, T>::type
141 foo(T t) { return t; }
144 The `disable_if_c` template is provided as well, and has the
145 same functionality as `enable_if_c` except for the negated
146 condition. The following function is enabled for all
147 non-arithmetic types.
151 typename disable_if_c<boost::is_arithmetic<T>::value, T>::type
152 bar(T t) { return t; }
155 For easier syntax in some cases and interoperation with
156 Boost.MPL we provide versions of the `enable_if` templates
157 taking any type with a `bool` member constant named `value` as
158 the condition argument. The MPL `bool_`, `and_`, `or_`, and
159 `not_` templates are likely to be useful for creating such
160 types. Also, the traits classes in the Boost.Type_traits
161 library follow this convention. For example, the above example
162 function `foo` can be alternatively written as:
166 typename enable_if<boost::is_arithmetic<T>, T>::type
167 foo(T t) { return t; }
172 [section:using_enable_if Using enable_if]
174 The `enable_if` templates are defined in
175 `boost/utility/enable_if.hpp`, which is included by
178 With respect to function templates, `enable_if` can be used in
179 multiple different ways:
181 * As the return type of an instantiatied function
182 * As an extra parameter of an instantiated function
183 * As an extra template parameter (useful only in a compiler
184 that supports C++0x default arguments for function template
185 parameters, see [link
186 core.enable_if.using_enable_if.enable_if_0x Enabling function
187 templates in C++0x] for details.
189 In the previous section, the return type form of `enable_if`
190 was shown. As an example of using the form of `enable_if` that
191 works via an extra function parameter, the `foo` function in
192 the previous section could also be written as:
197 typename enable_if<boost::is_arithmetic<T> >::type* dummy = 0);
200 Hence, an extra parameter of type `void*` is added, but it is
201 given a default value to keep the parameter hidden from client
202 code. Note that the second template argument was not given to
203 `enable_if`, as the default `void` gives the desired behavior.
205 Which way to write the enabler is largely a matter of taste,
206 but for certain functions, only a subset of the options is
209 * Many operators have a fixed number of arguments, thus
210 `enable_if` must be used either in the return type or in an
211 extra template parameter.
212 * Functions that have a variadic parameter list must use either
213 the return type form or an extra template parameter.
214 * Constructors do not have a return type so you must use either
215 an extra function parameter or an extra template parameter.
216 * Constructors that have a variadic parameter list must an
217 extra template parameter.
218 * Conversion operators can only be written with an extra
221 [section:enable_if_0x Enabling function templates in C++0x]
223 In a compiler which supports C++0x default arguments for
224 function template parameters, you can enable and disable
225 function templates by adding an additional template parameter.
226 This approach works in all situations where you would use
227 either the return type form of `enable_if` or the function
228 parameter form, including operators, constructors, variadic
229 function templates, and even overloaded conversion operations.
234 #include <boost/type_traits/is_arithmetic.hpp>
235 #include <boost/type_traits/is_pointer.hpp>
236 #include <boost/utility/enable_if.hpp>
241 // A constructor that works for any argument list of size 10
242 template< class... T,
243 typename boost::enable_if_c< sizeof...( T ) == 10,
247 // A conversion operation that can convert to any arithmetic type
249 typename boost::enable_if< boost::is_arithmetic< T >,
253 // A conversion operation that can convert to any pointer type
255 typename boost::enable_if< boost::is_pointer< T >,
263 test test_( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );
266 test fail_construction( 1, 2, 3, 4, 5 );
268 // Works by calling the conversion operator enabled for arithmetic types
269 int arithmetic_object = test_;
271 // Works by calling the conversion operator enabled for pointer types
272 int* pointer_object = test_;
275 struct {} fail_conversion = test_;
281 [section Enabling template class specializations]
283 Class template specializations can be enabled or disabled with
284 `enable_if`. One extra template parameter needs to be added for
285 the enabler expressions. This parameter has the default value
289 template <class T, class Enable = void>
293 class A<T, typename enable_if<is_integral<T> >::type> { ... };
296 class A<T, typename enable_if<is_float<T> >::type> { ... };
299 Instantiating `A` with any integral type matches the first
300 specialization, whereas any floating point type matches the
301 second one. All other types match the primary template.
302 The condition can be any compile-time boolean expression that
303 depends on the template arguments of the class. Note that
304 again, the second argument to `enable_if` is not needed; the
305 default (`void`) is the correct value.
307 The `enable_if_has_type` template is usable this scenario but instead of
308 using a type traits to enable or disable a specialization, it use a
309 SFINAE context to check for the existence of a dependent type inside
310 its parameter. For example, the following structure extracts a dependent
311 `value_type` from T if and only if `T::value_type` exists.
314 template <class T, class Enable = void>
315 class value_type_from
321 class value_type_from<T, typename enable_if_has_type<typename T::value_type>::type>
323 typedef typename T::value_type type;
329 [section Overlapping enabler conditions]
331 Once the compiler has examined the enabling conditions and
332 included the function into the overload resolution set, normal
333 C++ overload resolution rules are used to select the best
334 matching function. In particular, there is no ordering between
335 enabling conditions. Function templates with enabling
336 conditions that are not mutually exclusive can lead to
337 ambiguities. For example:
341 typename enable_if<boost::is_integral<T>, void>::type
345 typename enable_if<boost::is_arithmetic<T>, void>::type
349 All integral types are also arithmetic. Therefore, say, for the
350 call `foo(1)`, both conditions are true and both functions are
351 thus in the overload resolution set. They are both equally good
352 matches and thus ambiguous. Of course, more than one enabling
353 condition can be simultaneously true as long as other arguments
354 disambiguate the functions.
356 The above discussion applies to using `enable_if` in class
357 template partial specializations as well.
361 [section:enable_if_lazy Lazy enable_if]
363 In some cases it is necessary to avoid instantiating part of a
364 function signature unless an enabling condition is true. For
368 template <class T, class U> class mult_traits;
370 template <class T, class U>
371 typename enable_if<is_multipliable<T, U>,
372 typename mult_traits<T, U>::type>::type
373 operator*(const T& t, const U& u) { ... }
376 Assume the class template `mult_traits` is a traits class
377 defining the resulting type of a multiplication operator. The
378 `is_multipliable` traits class specifies for which types to
379 enable the operator. Whenever `is_multipliable<A, B>::value` is
380 `true` for some types `A` and `B`, then
381 `mult_traits<A, B>::type` is defined.
383 Now, trying to invoke (some other overload) of `operator*`
384 with, say, operand types `C` and `D` for which
385 `is_multipliable<C, D>::value` is `false` and
386 `mult_traits<C, D>::type` is not defined is an error on some
387 compilers. The SFINAE principle is not applied because the
388 invalid type occurs as an argument to another template. The
389 `lazy_enable_if` and `lazy_disable_if` templates (and their
390 `_c` versions) can be used in such situations:
393 template<class T, class U>
394 typename lazy_enable_if<is_multipliable<T, U>,
395 mult_traits<T, U> >::type
396 operator*(const T& t, const U& u) { ... }
398 ``The second argument of `lazy_enable_if` must be a class type
399 that defines a nested type named `type` whenever the first
400 parameter (the condition) is true.
402 [note Referring to one member type or static constant in a
403 traits class causes all of the members (type and static
404 constant) of that specialization to be instantiated.
405 Therefore, if your traits classes can sometimes contain invalid
406 types, you should use two distinct templates for describing the
407 conditions and the type mappings. In the above example,
408 `is_multipliable<T, U>::value` defines when
409 `mult_traits<T, U>::type` is valid.]
413 [section Compiler workarounds]
415 Some compilers flag functions as ambiguous if the only
416 distinguishing factor is a different condition in an enabler
417 (even though the functions could never be ambiguous). For
418 example, some compilers (e.g. GCC 3.2) diagnose the following
419 two functions as ambiguous:
423 typename enable_if<boost::is_arithmetic<T>, T>::type
427 typename disable_if<boost::is_arithmetic<T>, T>::type
431 Two workarounds can be applied:
433 * Use an extra dummy parameter which disambiguates the
434 functions. Use a default value for it to hide the parameter
435 from the caller. For example:
437 template <int> struct dummy { dummy(int) {} };
440 typename enable_if<boost::is_arithmetic<T>, T>::type
441 foo(T t, dummy<0> = 0);
444 typename disable_if<boost::is_arithmetic<T>, T>::type
445 foo(T t, dummy<1> = 0);
447 * Define the functions in different namespaces and bring them
448 into a common namespace with `using` declarations:
452 typename enable_if<boost::is_arithmetic<T>, T>::type
458 typename disable_if<boost::is_arithmetic<T>, T>::type
465 Note that the second workaround above cannot be used for
466 member templates. On the other hand, operators do not accept
467 extra arguments, which makes the first workaround unusable.
468 As the net effect, neither of the workarounds are of
469 assistance for templated operators that need to be defined as
470 member functions (assignment and subscript operators).
476 [section Acknowledgements]
478 We are grateful to Howard Hinnant, Jason Shirk, Paul
479 Mensonides, and Richard Smith whose findings have
480 influenced the library.
486 * [#REF1] \[1\] Jaakko J\u00E4rvi, Jeremiah Willcock, Howard
487 Hinnant, and Andrew Lumsdaine. Function overloading based on
488 arbitrary properties of types. /C++ Users Journal/,
489 21(6):25--32, June 2003.
490 * [#REF2] \[2\] Jaakko J\u00E4rvi, Jeremiah Willcock, and
491 Andrew Lumsdaine. Concept-controlled polymorphism. In Frank
492 Pfennig and Yannis Smaragdakis, editors, /Generative
493 Programming and Component Engineering/, volume 2830 of
494 /LNCS/, pages 228--244. Springer Verlag, September 2003.
495 * [#REF3] \[3\] David Vandevoorde and Nicolai M. Josuttis.
496 /C++ Templates: The Complete Guide/. Addison-Wesley, 2002.