Issue 233277
Summary [clang-tidy] modernize-type-traits suggestion to use `_v` is wrong inside constraints
Labels clang-tidy
Assignees
Reporter nikola-benes
    The expressions `std::tuple_size_v<T>` and `std::tuple_size<T>::value` are not equivalent when used inside constraints (such as the `require` _expression_ or the definition of a concept). This is because `std::tuple_size_v<T>` is not SFINAE-friendly (the variable is always declared for every T). Consider the following code:

```Cpp
template <typename T>
bool check() {
    if constexpr ( requires { std::tuple_size<T>::value; })
        return true;
 else
        return false;
}
```

Here, `check<int>()` returns `false`. Clang-tidy-23 suggests:

```
 warning: use c++17 style variable templates [modernize-type-traits]
      |     if constexpr ( requires { std::tuple_size<T>::value; })
      |                               ^ ~~~~~~~
      | _v
```

However, if we replace `std::tuple_size<T>::value` with `std::tuple_size_v<T>`, `check<int>()` returns `true`.

The situation is even worse when we actually try to use the tuple size, e.g., in concept definitions. Consider the code:

```Cpp
template <typename T>
concept is_pair = std::tuple_size<T>::value == 2;

template <typename T>
bool check() {
    return is_pair<T>;
}
```

Now, `check<int>` again returns `false`. However, if we follow clang-tidy's suggestion and use `std::tuple_size_v<T>`, calling `check<int>()` **does not compile**:

```
error: implicit instantiation of undefined template 'std::tuple_size<int>'
      |     inline constexpr size_t tuple_size_v = tuple_size<_Tp>::value;
      | ^
note: in instantiation of variable template specialization 'std::tuple_size_v<int>' requested here
      | concept is_pair = std::tuple_size_v<T> == 2;
      |                        ^
note: while substituting template arguments into constraint _expression_ here
      | concept is_pair = std::tuple_size_v<T> == 2;
      | ^~~~~~~~~~~~~~~~~~~~~~~~~
note: while checking the satisfaction of concept 'is_pair<int>' requested here
      |         return is_pair<T>;
      | ^~~~~~~~~~
note: in instantiation of function template specialization 'check<int>' requested here
      |         return check<int>();
      |                ^
note: template is declared here
 |     struct tuple_size;
      |            ^
```

It seems that the same issue affects all the `_v` variable shortcuts. (The type `_t` shortcuts seem to be fine, however.)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to