-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnableIf.cpp
80 lines (65 loc) · 1.58 KB
/
EnableIf.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/enable-if
#include "idioms.h"
#include <type_traits>
#include <stdlib.h>
#include <string.h>
#include <iostream>
template <bool, class T = void>
struct enable_if
{
};
template <class T>
struct enable_if < true, T>
{
typedef T type;
};
struct SimpleStruct
{
int x;
};
struct NonPodStruct
{
NonPodStruct(int v)
: x(v)
{
}
int x;
};
/*
template<typename _T>
_T* copy(const _T& origin, typename enable_if<std::is_pod<_T>::value>::type* = nullptr)
{
std::cout << "POD" << std::endl;
_T* p = reinterpret_cast<_T*> (malloc(sizeof (_T)));
memcpy(p, &origin, sizeof (_T));
return p;
}
template<typename _T>
_T* copy(const _T& origin, typename enable_if<!std::is_pod<_T>::value && std::is_copy_constructible<_T>::value>::type* = nullptr)
{
std::cout << "Copy constructor" << std::endl;
return new _T(origin);
}
*/
template<class _T>
typename enable_if<std::is_pod<_T>::value, _T*>::type copy(const _T& origin)
{
std::cout << "POD" << std::endl;
_T* p = reinterpret_cast<_T*> (malloc(sizeof (_T)));
memcpy(p, &origin, sizeof (_T));
return p;
}
template<class _T>
typename enable_if<!std::is_pod<_T>::value && std::is_copy_constructible<_T>::value, _T*>::type copy(const _T& origin)
{
std::cout << "Copy constructor" << std::endl;
return new _T(origin);
}
void testEnableIf()
{
SimpleStruct s;
s.x = 10;
SimpleStruct* pCopy = copy(s);
NonPodStruct np(2);
NonPodStruct* pNonCopy = copy(np);
}