std::is_function是如何实现的?
How is std::is_function implemented?
以下 std::is_function
的实现方式如何?
template<class T>
struct is_function : std::integral_constant<
bool,
!std::is_const<const T>::value && !std::is_reference<T>::value
> {};
(来自 CPP Reference)
在我看来,int
将是此定义下的函数。我错过了什么?
让我们回顾一下出现的条件:
如果 const T
不是 const(const
并不真正适用于函数类型,因为函数不是对象),并且 T
不是引用(const
不出于同样的原因也不适用于引用),它是一种函数类型。 int
(或任何其他非函数非引用类型)不适合,因为 is_const<const int>::value
是 true
。
根据C++17 Standard §11.3.5 Functions / section 7:(强调我的)
The effect of a cv-qualifier-seq in a function declarator is not the
same as adding cv-qualification on top of the function type. In the
latter case, the cv-qualifiers are ignored. [ Note: A function type
that has a cv-qualifier-seq is not a cv-qualified type; there are no
cv-qualified function types. — end note ] [...]
语言中只有两类类型不能具有常量限定:引用类型和函数类型。因此,如果 const T
不是 const 限定类型,则意味着 T
要么是函数类型,要么是引用类型。如果您可以排除引用类型,那么您将只剩下函数类型。
请注意,带有 cv 限定符的函数类型,例如 int(int) const
,不是 const 限定类型。这是一个 "abominable function type" 的例子,它唯一的实际用途是组合或分解指向成员函数的指针类型。类型 int(int) const
无法通过在 int(int)
之上添加 const 限定来获得。相反,const
适用于隐含的对象参数。
以下 std::is_function
的实现方式如何?
template<class T>
struct is_function : std::integral_constant<
bool,
!std::is_const<const T>::value && !std::is_reference<T>::value
> {};
(来自 CPP Reference)
在我看来,int
将是此定义下的函数。我错过了什么?
让我们回顾一下出现的条件:
如果 const T
不是 const(const
并不真正适用于函数类型,因为函数不是对象),并且 T
不是引用(const
不出于同样的原因也不适用于引用),它是一种函数类型。 int
(或任何其他非函数非引用类型)不适合,因为 is_const<const int>::value
是 true
。
根据C++17 Standard §11.3.5 Functions / section 7:(强调我的)
The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored. [ Note: A function type that has a cv-qualifier-seq is not a cv-qualified type; there are no cv-qualified function types. — end note ] [...]
语言中只有两类类型不能具有常量限定:引用类型和函数类型。因此,如果 const T
不是 const 限定类型,则意味着 T
要么是函数类型,要么是引用类型。如果您可以排除引用类型,那么您将只剩下函数类型。
请注意,带有 cv 限定符的函数类型,例如 int(int) const
,不是 const 限定类型。这是一个 "abominable function type" 的例子,它唯一的实际用途是组合或分解指向成员函数的指针类型。类型 int(int) const
无法通过在 int(int)
之上添加 const 限定来获得。相反,const
适用于隐含的对象参数。