为什么可以用 std::is_const 和 std::is_reference 来实现 std::is_function ?

问题描述 投票:0回答:2

以下如何实现

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参考

在我看来,

int
将是这个定义下的一个函数。我错过了什么?

c++ templates std sfinae type-traits
2个回答
79
投票

让我们回顾一下出现的条件:
如果

const T
不是 const(
const
并不真正适用于函数类型,因为函数不是对象),并且
T
不是引用(
const
也不适用于引用)同样的原因),它是一个函数类型。
int
(或任何其他非功能非引用类型)不适合,因为
is_const<const int>::value
true

根据C++17标准§11.3.5函数/第7节:(强调我的)

函数声明符中 cv-qualifier-seq 的作用不是 与在函数类型之上添加 cv 限定相同。在里面 在后一种情况下,简历限定符将被忽略。 [注:A函数类型 具有 cv-qualifier-seq 的不是 cv 限定类型;没有 cv 限定的函数类型。 — 尾注] [...]


61
投票

语言中只有两类类型不能具有 const 限定:引用类型和函数类型。因此,如果

const T
不能成为 const 限定类型,则意味着
T
是函数类型或引用类型。如果您可以排除引用类型,那么您就只剩下函数类型了。

请注意,带有 cv 限定符的函数类型(例如

int(int) const
不是 const 限定类型。这是“令人讨厌的函数类型”的一个示例,其唯一真正的用途是组合或分解指向成员函数类型的指针。类型
int(int) const
无法通过在
int(int)
之上添加 const 限定来获得。相反,
const
适用于隐含的对象参数。

© www.soinside.com 2019 - 2024. All rights reserved.