Why are type_traits implemented with specialized template structs instead of constexpr?

后端 未结 5 1824
别跟我提以往
别跟我提以往 2021-01-12 00:40

Is there any reason why the standard specifies them as template structs instead of simple boolean constexpr?

In an additional question that

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 01:07

    One reason is that constexpr functions can't provide a nested type member, which is useful in some meta-programming situations.

    To make it clear, I'm not talking only of transformation traits (like make_unsigned) that produce types and obviously can't be made constexpr functions. All type traits provide such a nested type member, even unary type traits and binary type traits. For example is_void::type is false_type.

    Of course, this could be worked around with std::integral_constant()>, but it wouldn't be as practical.

    In any case, if you really want function-like syntax, that is already possible. You can just use the traits constructor and take advantage of the constexpr implicit conversion in integral_constant:

    static_assert(std::is_void(), "void is void; who would have thunk?");
    

    For transformation traits you can use a template alias to obtain something close to that syntax:

    template 
    using enable_if = typename std::enable_if::type;
    // usage:
    // template  enable_if(), int> f();
    //
    // make_unsigned x;
    

提交回复
热议问题