Project

General

Profile

Talk #3188 » ex1_type_deduction.cpp

Example 1: Template deduction - Glesaaen, Jonas, 2016-01-27 17:59

 
1
/*
2
 * Created: 27-01-2016
3
 * Modified: Wed 27 Jan 2016 17:54:20 CET
4
 * Author: Jonas R. Glesaaen (jonas@glesaaen.com)
5
 */
6

    
7
#include<iostream>
8
#include<utility>
9
#include<boost/type_index.hpp>
10

    
11
using boost::typeindex::type_id_with_cvr;
12

    
13
// Template type deducion case 1
14
// ParamType is a reference or pointer but not universal reference
15
template <typename T>
16
void f(T& x)
17
{
18
  std::cout << "T: "
19
    << type_id_with_cvr<T>().pretty_name() << ",\t"
20
    << "x: "
21
    << type_id_with_cvr<decltype(x)>().pretty_name() << "\n";
22
}
23

    
24
// Template type deducion case 2
25
// ParamType is a not universal reference
26
template <typename T>
27
void g(T&& x)
28
{
29

    
30
  std::cout << "T: "
31
    << type_id_with_cvr<T>().pretty_name() << ",\t"
32
    << "x: "
33
    << type_id_with_cvr<decltype(x)>().pretty_name() << "\n";
34
}
35

    
36
// Template type deducion case 3
37
// ParamType is a not a reference nor a pointer
38
template <typename T>
39
void h(T x)
40
{
41
  std::cout << "T: "
42
    << type_id_with_cvr<T>().pretty_name() << ",\t"
43
    << "x: "
44
    << type_id_with_cvr<decltype(x)>().pretty_name() << "\n";
45
}
46

    
47
int main(int, char**)
48
{
49
  int x;
50
  int& rx = x;
51
  const int & crx = x;
52

    
53
  std::cout << "template <typename T>\n"
54
    << "void f(T& x)" << "\n";
55

    
56
  f(x);
57
  f(rx);
58
  f(crx);
59

    
60
  std::cout << "\n" << "template <typename T>\n"
61
    << "void g(T&& x)" << "\n";
62

    
63
  g(x);
64
  g(rx);
65
  g(crx);
66
  g(27);
67

    
68
  std::cout << "\n" << "template <typename T>\n"
69
    << "void h(T x)" << "\n";
70

    
71
  h(x);
72
  h(rx);
73
  h(crx);
74
  
75
}
(1-1/7)