首页 > 解决方案 > 对于什么 T `std::declval()` 没有匹配函数?

问题描述

我惊讶地发现,对于某些T,decltype(std::declval<T>())是不合法的:

#include <utility>

template<typename T>
using Alias = decltype(std::declval<T>());

// as expected
using A1 = Alias<int>;
using A2 = Alias<int(int)>;

// error: no matching function for call to 'declval<...>()'
using A3 = Alias<int(int) const>;
using A4 = Alias<int(int) volatile>;
using A5 = Alias<int(int) &>;
using A6 = Alias<int(int) &&>;
// and all combinations of the above

cppreference似乎并未表明此错误是预期的。

还有其他declval<T>不能使用的类型吗?规范在哪里定义这些?

标签: c++language-lawyerdeclval

解决方案


每个[declval]的签名declval是:

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

add_rvalue_reference_t<T>因此,如果不能作为返回类型说明符出现,则该调用是格式错误的。

合格的函数类型有一个特殊的规则:

具有cv-qualifier-seqref-qualifier的函数类型 (包括由typedef-name ([dcl.typedef], [temp.param]) 命名的类型)应仅显示为:

  • (6.1) 非静态成员函数的函数类型,

  • (6.2) 指向成员的指针所指的函数类型,

  • (6.3) 函数 typedef 声明或alias-declaration的顶级函数类型,

  • (6.4) type-parameter的默认参数中的type-id,或

  • (6.5)类型参数([temp.arg.type])的模板参数的类型ID 。

它们不能是返回类型说明符。

查看Types,我很确定合格的函数类型是唯一的情况。


推荐阅读