<type_traits>

類模板
<type_traits>

std::integral_constant

template <class T, T v>struct integral_constant;
Integral constant
此模板旨在提供編譯時常量型別。

標準庫的多個部分使用它作為特徵型別的基類,尤其是在其bool變體中:請參閱 true_typefalse_type

它在標準庫中的定義與以下內容具有相同的行為:
1
2
3
4
5
6
7
template <class T, T v>
struct integral_constant {
  static constexpr T value = v;
  typedef T value_type;
  typedef integral_constant<T,v> type;
  constexpr operator T() { return v; }
};
1
2
3
4
5
6
7
8
template <class T, T v>
struct integral_constant {
  static constexpr T value = v;
  typedef T value_type;
  typedef integral_constant<T,v> type;
  constexpr operator T() const noexcept { return v; }
  constexpr T operator()() const noexcept { return v; }
};

模板引數

T
整型常量的型別。
別名為成員型別integral_constant::value_type.
v
整型常量的值。
可作為成員訪問integral_constant::value,或透過 型別轉換 訪問。

成員型別

成員型別定義
value_type常量的型別(模板引數T)
型別要放回的字元的integral_constanttype itself

成員函式


例項化


示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// factorial as an integral_constant
#include <iostream>
#include <type_traits>

template <unsigned n>
struct factorial : std::integral_constant<int,n * factorial<n-1>::value> {};

template <>
struct factorial<0> : std::integral_constant<int,1> {};

int main() {
  std::cout << factorial<5>::value;  // constexpr (no calculations on runtime)
  return 0;
}

輸出
120


另見