class template
<type_traits>

std::common_type

template <class... Types> struct common_type;
Common type
Obtains the common type for the types in the Types list to which all of them can be converted.

The selected type is aliased as member type common_type::type.

It is defined with a behavior equivalent to:
1
2
3
4
5
6
7
8
9
10
11
12
13
template <class... Types> 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;
};

1
2
3
4
5
6
7
8
9
10
11
12
13
template <class... Types> struct common_type;

template <class T> struct common_type<T> {
  typedef decay_t<T> type;
};

template <class T, class U> struct common_type<T,U> {
  typedef decay_t<decltype(true?declval<T>():declval<U>())> type;
};

template <class T, class U, class... V> struct common_type<T,U,V...> {
  typedef common_type_t<common_type_t<T,U>, V...> type;
};


This definition covers all implicit conversions between types, but the class can be overloaded to provide a common type for explicit conversions.

This class is overloaded for the standard types of the <chrono> header duration and time_point.

Template parameters

Types
A list of types, each being either a complete type or void (possibly cv-qualified).

Member types

member typedefinition
typeThe common type for all Types.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// common_type example
#include <iostream>
#include <type_traits>

struct Base{};
struct Derived : Base {};

int main() {

  typedef std::common_type<char,short,int>::type A;           // int
  typedef std::common_type<float,double>::type B;             // double
  typedef std::common_type<Derived,Base>::type C;             // Base
  typedef std::common_type<Derived*,Base*>::type D;           // Base*
  typedef std::common_type<const int,volatile int>::type E;   // int

  std::cout << std::boolalpha;
  std::cout << "typedefs of int:" << std::endl;
  std::cout << "A: " << std::is_same<int,A>::value << std::endl;
  std::cout << "B: " << std::is_same<int,B>::value << std::endl;
  std::cout << "C: " << std::is_same<int,C>::value << std::endl;
  std::cout << "D: " << std::is_same<int,D>::value << std::endl;
  std::cout << "E: " << std::is_same<int,E>::value << std::endl;

  return 0;
}


Output:
typedefs of int:
A: true
B: false
C: false
D: false
E: true

See also

<type_traits>