gpt4 book ai didi

c++ - 为什么专门化 type_trait 会导致未定义的行为?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:11:06 27 4
gpt4 key购买 nike

讨论

根据标准§20.10.2/1 Header <type_traits>概要 [meta.type.synop]:

1 The behavior of a program that adds specializations for any of the class templates defined in this subclause is undefined unless otherwise specified.

这个特定的子句与 STL 应该是可扩展的一般概念相矛盾,并阻止我们扩展类型特征,如下例所示:

namespace std {
template< class T >
struct is_floating_point<std::complex<T>> : std::integral_constant
<
bool,
std::is_same<float, typename std::remove_cv<T>::type>::value ||
std::is_same<double, typename std::remove_cv<T>::type>::value ||
std::is_same<long double, typename std::remove_cv<T>::type>::value
> {};
}

LIVE DEMO

哪里std::is_floating_point扩展为处理 complex具有底层浮点类型的数字。

问题

  1. 标准化委员会决定类型性状不应专门化的原因是什么。
  2. 是否有取消此限制的 future 计划。

最佳答案

对于主要类型类别,is_floating_point是一个,有一个设计不变量:

For any given type T, exactly one of the primary type categories has a value member that evaluates to true.

引用:(20.10.4.1 初级类型分类[me​​ta.unary.cat])

程序员在检查一些未知的泛型类型时可以依赖泛型代码中的这个不变量 T : IE。如果is_class<T>::valuetrue , 那么我们就不需要检查 is_floating_point<T>::value .我们保证后者是 false .

这是一张图代表主要和复合类型特征(此图顶部的叶子是主要类别)。

http://howardhinnant.github.io/TypeHiearchy.pdf

如果允许有(例如)std::complex<double>is_class 都回答正确和 is_floating_point ,这个有用的不变量将被破坏。程序员将无法再依赖这样一个事实:如果 is_floating_point<T>::value == true , 然后 T必须是 float 之一, double , 或 long double .

现在有一些特征,标准确实“另有说明”,并且允许对用户定义类型进行专门化。 common_type<T, U>就是这样的特质。

对于主要和复合类型特征,没有计划放宽对这些特征进行特化的限制。这样做会损害这些特征对可以在 C++ 中生成的每个单一类型进行精确和唯一分类的能力。

关于c++ - 为什么专门化 type_trait 会导致未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345486/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com