49 lines · plain
1.. title:: clang-tidy - bugprone-incorrect-enable-if2 3bugprone-incorrect-enable-if4============================5 6Detects incorrect usages of ``std::enable_if`` that don't name the nested7``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 type11parameter with a default type equal to12``typename std::enable_if<condition>::type``. If the author forgets to name13the nested type ``type``, then the code will always consider the candidate14template even if the condition is not met.15 16Below are some examples of code using ``std::enable_if`` correctly and17incorrect 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 if28 // T::some_trait is not true, the function will still be considered in the29 // set of function candidates. It can either incorrectly select the function30 // when it should not be a candidates, and/or lead to hard compile errors31 // if the body of the template does not compile if the condition is not32 // 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 the41likelihood of this error. C++20 introduces constraints, which generally42supersede the use of ``std::enable_if``. See43:doc:`modernize-type-traits <../modernize/type-traits>` for another tool44that will replace ``std::enable_if`` with45``std::enable_if_t``, and see46:doc:`modernize-use-constraints <../modernize/use-constraints>` for another47tool that replaces ``std::enable_if`` with C++20 constraints. Consider these48newer mechanisms where possible.49