| 1 |
.. title:: clang-tidy - bugprone-incorrect-enable-if |
| 2 |
|
| 3 |
bugprone-incorrect-enable-if |
| 4 |
============================ |
| 5 |
|
| 6 |
Detects incorrect usages of ``std::enable_if`` that don't name the nested |
| 7 |
``type`` type. |
| 8 |
|
| 9 |
In C++11 introduced ``std::enable_if`` as a convenient way to leverage SFINAE. |
| 10 |
One form of using ``std::enable_if`` is to declare an unnamed template type |
| 11 |
parameter with a default type equal to |
| 12 |
``typename std::enable_if<condition>::type``. If the author forgets to name |
| 13 |
the nested type ``type``, then the code will always consider the candidate |
| 14 |
template even if the condition is not met. |
| 15 |
|
| 16 |
Below are some examples of code using ``std::enable_if`` correctly and |
| 17 |
incorrect 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 |
|
| 40 |
C++14 introduced the trait helper ``std::enable_if_t`` which reduces the |
| 41 |
likelihood of this error. C++20 introduces constraints, which generally |
| 42 |
supersede the use of ``std::enable_if``. See |
| 43 |
:doc:`modernize-type-traits <../modernize/type-traits>` for another tool |
| 44 |
that will replace ``std::enable_if`` with |
| 45 |
``std::enable_if_t``, and see |
| 46 |
:doc:`modernize-use-constraints <../modernize/use-constraints>` for another |
| 47 |
tool that replaces ``std::enable_if`` with C++20 constraints. Consider these |
| 48 |
newer mechanisms where possible. |