-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate_arg_deduct.cpp
50 lines (43 loc) · 1.18 KB
/
template_arg_deduct.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <type_traits>
struct Data
{
int value;
};
template<typename ValueType>
static void function(ValueType& value, auto visitor)
{
visitor(value);
}
template<typename T>
struct remove_pointer
{
typedef T type;
};
template<typename T> struct remove_pointer<T*>
{
typedef T type;
};
template<typename T>
struct is_refers_to_const_value
{
static constexpr bool value = std::is_const<typename remove_pointer<typename std::remove_reference<T>::type>::type>::value;
};
template<typename T> requires(std::is_pointer<T>::value)
static void functionWrapper(T& t)
{
// NOTE: if T is const Data*
// then decltype(t->value) would return 'int'
// That means decltype() doesn't care about the cv-qualification of t when t->value is passed into it!
// Therefore we need to add const qualification based on if t refers to a constant value
using ValueType = typename std::conditional<is_refers_to_const_value<decltype(t)>::value,
typename std::add_const<decltype(t->value)>::type,
decltype(t->value)>::type;
function(t->value, [](ValueType& value) { });
}
static void myFunction()
{
Data* data = new Data { };
functionWrapper(data);
const Data* const_data = data;
functionWrapper(const_data);
}