Search code examples
c++metaprogrammingc++20type-traits

The problem of libstdc++‘s implementation of std::declval


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?


Solution

  • The example is ill-formed, because the restriction for std::declval is actually on the expression where declval is named, not on whether the abstract virtual machine would actually evaluate its call.

    The requirement on std::declval is [declval].2

    Mandates: This function is not odr-used ([basic.def.odr]).

    where "Mandates" means ([structure.specifications]/(3.2))

    Mandates: the conditions that, if not met, render the program ill-formed.

    In [basic.def.odr]/7:

    A function is odr-used if it is named by a potentially-evaluated expression or conversion.

    And in [basic.def.odr]/2:

    An expression or conversion is potentially evaluated unless it is an unevaluated operand ([expr.prop]), a subexpression thereof, or a conversion in an initialization or conversion sequence in such a context.

    Note the expression type<int>() in the last line is an unevaluated operand. But the distinct expression std::declval<T>() in the instantiated definition of type is potentially evaluated. It doesn't matter that ignoring that, it would not actually be evaluated.

    So actually the libc++ and MSVC-STL implementations are incorrect, because an ill-formed program should be diagnosed unless otherwise noted.