Post

C++ Tips : decltype

decltype.

C++ Tips : decltype

My C++ Tips

decltype


Decltype

  • C++11

  • deduce the type of value/expression at compile time.
  • unevaluated context (No opcode generated)

decltype(value) && decltype(expression)

  • if expr PR value, result: T
  • if expr L value, result: T&
  • if expr X value, result: T&
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
26
27
28
29
30
31
32
33
#include <iostream>
#include <type_traits>

int main() 
{
	std::cout << std::boolalpha;

	int x = 10;
	std::cout << std::is_same_v<decltype(x), int> << '\n';
	
	std::cout << std::is_same_v<decltype(++x), int&> << '\n';
	std::cout << std::is_same_v<decltype(x++), int> << '\n';

	std::cout << std::is_same_v<decltype( (x) ), int&> << '\n'; // important (x) -> expression
	std::cout << std::is_same_v<decltype(x + 4 ), int> << '\n';
	
	const int cx = 5;
	std::cout << std::is_same_v<decltype(cx), const int> << '\n';

	const int* ptr = &x;
	std::cout << std::is_same_v<decltype(ptr), const int*> << '\n';

	const int* const cptr = &x;
	std::cout << std::is_same_v<decltype(cptr), const int* const> << '\n';

	int arr[5];
	std::cout << std::is_same_v<decltype(arr), int[5]> << '\n';
	std::cout << std::is_same_v<decltype(arr), int[6]> << '\n'; // FALSE

	int* p = &x;
	std::cout << std::is_same_v<decltype(p), int*> << '\n';
	std::cout << std::is_same_v<decltype(*p), int&> << '\n';
}

Try here.


decltype vs auto

  • auto deduces the value type
  • decltype deduces the exact type
1
2
3
4
5
int x = 5;
int& ref = x;

auto a = ref;          // int
decltype(ref) b = x;   // int&
This post is licensed under CC BY 4.0 by the author.