Unlike libc++ or MSVC-STL that only declares the function signature of std::declval
, libstdc++ defines the function body for std::declval
, and uses static_assert
internally to ensure that it must be used in unevaluated contexts:
template<typename _Tp, typename _Up = _Tp&&>
_Up
__declval(int);
template<typename _Tp>
_Tp
__declval(long);
template<typename _Tp>
auto
declval() noexcept -> decltype(__declval<_Tp>(0));
template<typename _Tp>
struct __declval_protector {
static const bool __stop = false;
};
template<typename _Tp>
auto
declval() noexcept -> decltype(__declval<_Tp>(0)) {
static_assert(__declval_protector<_Tp>::__stop,
"declval() must not be used!");
return __declval<_Tp>(0);
}
When we try to evaluate the return value of std::declval
, this static_assert
will be triggered:
auto x = std::declval<int>(); // static assertion failed: declval() must not be used!
But I found that in this implementation, the following code will also be rejected because static_assert
fails (godbolt):
#include <type_traits>
template<class T>
auto type() { return std::declval<T>(); }
using T = decltype(type<int>());
But it seems that std::declval
is still used in an unevaluated context since we have not actually evaluated it.
Is the above code well-formed? If so, is it a library implementation bug? How does the standard specify this?