<type_traits>

類模板
<type_traits>

std::add_const

template <class T> struct add_const;
新增const限定
獲取型別Tconst的頂層限定符。

轉換後的類型別名為成員型別add_const::type.

如果已知T如果 T 尚未被 const 限定,且不是引用或函式(這不能被 const 限定),則此型別與T const相同。否則,它是T不變。

請注意,此類僅使用另一種型別作為模型來獲取型別,但它不會在這些型別之間轉換值或物件。要顯式地為物件新增 const 限定,請使用const_cast可以使用。

模板引數

T
一個型別。

成員型別

成員型別定義
型別如果已知T如果不 const 限定,且不是引用或函式,則與T相同,但已 const 限定。
否則,T.

示例

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

int main() {
  typedef std::add_const<int>::type A;         // const int
  typedef std::add_const<const int>::type B;   // const int     (unchanged)
  typedef std::add_const<const int*>::type C;  // const int* const
  typedef std::add_const<int* const>::type D;  // int* const    (unchanged)
  typedef std::add_const<const int&>::type E;  // const int&    (unchanged)

  std::cout << std::boolalpha;
  std::cout << "checking constness:" << std::endl;
  std::cout << "A: " << std::is_const<A>::value << std::endl;
  std::cout << "B: " << std::is_const<B>::value << std::endl;
  std::cout << "C: " << std::is_const<C>::value << std::endl;
  std::cout << "D: " << std::is_const<D>::value << std::endl;
  std::cout << "E: " << std::is_const<E>::value << std::endl;

  return 0;
}

輸出
checking constness
A: true
B: true
C: true
D: true
E: false


另見