std::common_type implementation

前端 未结 3 859
清歌不尽
清歌不尽 2021-02-20 04:43

Just to see how it worked, I looked at the libstdc++ implementation of std::common_type in the header type_traits. I have to admit that I don\'t really

3条回答
  •  灰色年华
    2021-02-20 04:52

    First off, std::declval() yields an r-value of type T. Trying to do anything with the value will fail so it can only be used in an unevaluated context. Next, the ternary operator deduces its type as most specialized type common to both arguments (if there is no such type, it fails). So, the type of the expression

    true? declval(): declval()
    

    is the most specialized common type of T0 and T1. All what remains is to turn this expression into a type and making sure that it isn't evaluated. decltype(expr) does just this. Clearly, the two argument version of the beef of the logic: the others are there to deal with the corner case (one argument) and to leverage the two argument version to yield the common type of arbitrary types.

提交回复
热议问题