Why specializing a type_trait could result in undefined behaviour?

前端 未结 2 489
故里飘歌
故里飘歌 2020-12-30 10:45

Discussion

According to the standard §20.10.2/1 Header synopsis [meta.type.synop]:

1

2条回答
  •  难免孤独
    2020-12-30 11:13

    For the primary type categories, which is_floating_point is one, there is a design invariant:

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

    Reference: (20.10.4.1 Primary type categories [meta.unary.cat])

    Programmers can rely on this invariant in generic code when inspecting some unknown generic type T: I.e. if is_class::value is true, then we don't need to check is_floating_point::value. We are guaranteed the latter is false.

    Here is a diagram representing the primary and composite type traits (the leaves at the top of this diagram are the primary categories).

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

    If it was allowed to have (for example) std::complex answer true to both is_class and is_floating_point, this useful invariant would be broken. Programmers would no longer be able to rely on the fact that if is_floating_point::value == true, then T must be one of float, double, or long double.

    Now there are some traits, where the standard does "say otherwise", and specializations on user-defined types are allowed. common_type is such a trait.

    For the primary and composite type traits, there are no plans to relax the restriction of specializing these traits. Doing so would compromise the ability of these traits to precisely and uniquely classify every single type that can be generated in C++.

提交回复
热议问题