What is the purpose of std::common_type?

std::common_type was introduced for use with std::duration — if you add a std::duration<int> and a std::duration<short> then the result should be std::duration<int>. Rather than specifying an endless stream of allowed pairings, the decision was made to delegate to a separate template which found the result using the core language rules applicable to the ?: arithmetic-if operator.

People then saw that this template might be generally useful, and it was added as std::common_type, and extended to handle an arbitrary number of types. In the C++0x library it is only used for pairs of types though.

You should be able to use the new SFINAE rules to detect whether or not some instantiation of std::common_type is valid. I haven’t tried though. In most cases if there isn’t a “common type” then there isn’t anything meaningful you can do anyway, so a compile error is reasonable.

std::common_type is not magic — it follows the rules of ?:. If true?a:b will compile, std::common_type<decltype(a),decltype(b)>::type will give you the type of the result.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)