Search code examples
c++c++11language-lawyertemplate-instantiationdeclval

Understanding declval optimized implementation


Looking at libstdc++ source code, I found the following declval implementation:

template<typename _Tp, typename _Up = _Tp&&>
_Up __declval(int);  // (1)

template<typename _Tp>
_Tp __declval(long); // (2)

template<typename _Tp>
auto declval() noexcept -> decltype(__declval<_Tp>(0));

This implementation was proposed by Eric Niebler as a compile time optimization: he explains that overload resolution is faster than template instantiation.

However, I can't understand how it works. Specifically:

  1. In (1), why is using _Up better than just returning _Tp&& ?
  2. It seems that the overload (2) is never used. Why is it needed?

How all this prevents template instantiations, as opposed to the most naive implementation:

template<typename T>
T&& declval() noexcept;

Solution

  • The naive implementation is not fully correct. According to the Standard, declval is defined as ([declval]):

    template <class T> add_rvalue_reference_t<T> declval() noexcept;

    and for add_rvalue_reference<T> the Standard reads ([meta.trans.ref]):

    If T names a referenceable type then the member typedef type names T&&; otherwise, type names T.

    An example of a non-referenceable type is void. The second overload will be used in that case thanks to SFINAE.

    As to the first question, I don't see any special reason. _Tp&& should work just fine.