std::common_type
From Cppreference
Defined in header <type_traits>
|
||
template< class... T >
struct common_type; |
(C++11 feature) | |
Determines the common type among all types T..., that is the type of the (possibly mixed-mode) arithmetic expression such as T0() + T1() + ... + Tn().
Contents |
[edit] Member types
Name | Definition |
type | the common type for all T... |
[edit] Specializations
Custom specializations of the type trait std::common_type are allowed. The following specializations are already provided by the standard library:
|
specializes the std::common_type trait (class template specialization) |
|
|
specializes the std::common_type trait (class template specialization) |
[edit] Equivalent definition
template<class ...T> struct common_type; template<class T> struct common_type<T> { typedef T type; }; template<class T, class U> struct common_type<T, U> { typedef decltype(true ? declval<T>() : declval<U>()) type; }; template<class T, class U, class... V> struct common_type<T, U, V...> { typedef typename common_type<typename common_type<T, U>::type, V...>::type type; }; |
[edit] Example
Demonstrates mixed-mode arithmetic on a user-defined class
#include <iostream> #include <type_traits> template<typename T> struct Number { T n; }; template<typename T, typename U> Number<typename std::common_type<T, U>::type> operator+(const Number<T>& lhs, const Number<U>& rhs) { return {lhs.n + rhs.n}; } int main() { Number<int> n1 = {1}; Number<double> n2 = {2.3}; std::cout << (n1 + n2).n << '\n' << (n2 + n1).n << '\n'; }
Output:
3.3 3.3