<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/61300>61300</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Using `auto` keyword bypasses `if constexpr` validation rules
</td>
</tr>
<tr>
<th>Labels</th>
<td>
clang:frontend
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
paulsemel
</td>
</tr>
</table>
<pre>
The following code compiles correctly (https://godbolt.org/z/98dr4bsT8):
```c++
#include <type_traits>
template <typename T>
class raw_ptr {
public:
T* get() const { return nullptr; }
void ReportIfDangling() const {}
operator T*() const { return nullptr; }
};
template <typename T>
struct IsRawPtr : std::false_type {};
template <typename T>
struct IsRawPtr<raw_ptr<T>> : std::true_type {};
template <typename T>
inline constexpr bool IsRawPtrV = IsRawPtr<T>::value;
template <typename T>
class UnretainedWrapper {
public:
T* get() const {
// `ptr_` is either a `raw_ptr` or a regular C++ pointer.
if constexpr (IsRawPtrV<StorageType>) {
const auto& type = ptr_;
type.ReportIfDangling();
}
return ptr_;
}
using StorageType = T*;
// using StorageType = raw_ptr<T>;
StorageType ptr_;
};
int main() {
UnretainedWrapper<int> w;
w.get();
return 0;
}
```
Although, this doesn't respect https://en.cppreference.com/w/cpp/language/if:
> Outside a template, a discarded statement is fully checked
Changing the `get` method to:
```c++
T* get() const {
// `ptr_` is either a `raw_ptr` or a regular C++ pointer.
if constexpr (IsRawPtrV<StorageType>) {
ptr_.ReportIfDangling();
}
return ptr_;
}
```
will have the expected behaviour.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzUVk2PIjcQ_TXmUlpkbGjgwIGBQdpTos1schy57aLbWWNbdjUs-fWRaT5nd5VM9hTUAmSX672qelVtlbNtPOKCTZ7YZD1QHbUhLaLqXMYdukEdzHHx0iJsg3PhYH0DOhgEHXbROsygQ0qoyR2BiVlLFDOTSyY2TGyaYOrgaBhSw8TmLyY285lJ4zq_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