<type_traits>

類模板
<type_traits>

std::common_type

template <class... Types> struct common_type;
通用型別
獲取列表中的型別型別的“通用型別”,它們都可以轉換為該型別。

選定的類型別名為成員型別common_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 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;
};

此定義涵蓋了型別之間的所有隱式轉換,但該類可以被過載以提供顯式轉換的“通用型別”。

此類為 <chrono> 標頭檔案中的標準型別 durationtime_point 進行了過載。

模板引數

型別
型別列表,每個型別都是一個完整型別或 void(可能帶 cv 限定符)。

成員型別

成員型別定義
型別所有型別的通用型別型別.

示例

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;
}

輸出
typedefs of int:
A: true
B: false
C: false
D: false
E: true


另見