std::common_type

From Cppreference

Jump to: navigation, search
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:

std::common_type<std::chrono::duration>
specializes the std::common_type trait
(class template specialization)
std::common_type<std::chrono::time_point>
specializes the std::common_type trait
(class template specialization)

[edit] Equivalent definition

[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