xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/incorrect-enable-if.rst (revision a7bdaff7cad93e96ee9aaf3dc8b2a46c84717361)
1.. title:: clang-tidy - bugprone-incorrect-enable-if
2
3bugprone-incorrect-enable-if
4============================
5
6Detects incorrect usages of ``std::enable_if`` that don't name the nested
7``type`` type.
8
9In C++11 introduced ``std::enable_if`` as a convenient way to leverage SFINAE.
10One form of using ``std::enable_if`` is to declare an unnamed template type
11parameter with a default type equal to
12``typename std::enable_if<condition>::type``. If the author forgets to name
13the nested type ``type``, then the code will always consider the candidate
14template even if the condition is not met.
15
16Below are some examples of code using ``std::enable_if`` correctly and
17incorrect examples that this check flags.
18
19.. code-block:: c++
20
21  template <typename T, typename = typename std::enable_if<T::some_trait>::type>
22  void valid_usage() { ... }
23
24  template <typename T, typename = std::enable_if_t<T::some_trait>>
25  void valid_usage_with_trait_helpers() { ... }
26
27  // The below code is not a correct application of SFINAE. Even if
28  // T::some_trait is not true, the function will still be considered in the
29  // set of function candidates. It can either incorrectly select the function
30  // when it should not be a candidates, and/or lead to hard compile errors
31  // if the body of the template does not compile if the condition is not
32  // satisfied.
33  template <typename T, typename = std::enable_if<T::some_trait>>
34  void invalid_usage() { ... }
35
36  // The tool suggests the following replacement for 'invalid_usage':
37  template <typename T, typename = typename std::enable_if<T::some_trait>::type>
38  void fixed_invalid_usage() { ... }
39
40C++14 introduced the trait helper ``std::enable_if_t`` which reduces the
41likelihood of this error. C++20 introduces constraints, which generally
42supersede the use of ``std::enable_if``. See
43:doc:`modernize-type-traits <../modernize/type-traits>` for another tool
44that will replace ``std::enable_if`` with
45``std::enable_if_t``, and see
46:doc:`modernize-use-constraints <../modernize/use-constraints>` for another
47tool that replaces ``std::enable_if`` with C++20 constraints. Consider these
48newer mechanisms where possible.
49