-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_3_2.cpp
More file actions
57 lines (44 loc) · 1.79 KB
/
example_3_2.cpp
File metadata and controls
57 lines (44 loc) · 1.79 KB
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
#include <utility>
#include <cassert>
#include <iostream>
#include <array>
using namespace std;
struct ubiq_constructor {
size_t ignore;
template <class T> constexpr operator T&(); // Undefined, allows initialization of reference fields (T& and const T&)
};
template <class T, size_t... I>
auto enable_if_constructible(index_sequence<I...>) -> decltype(T{ ubiq_constructor{I}... });
template <class T, size_t N, class = void_t<>>
struct enable_if_constructible_t : std::false_type {};
template <class T, size_t N>
struct enable_if_constructible_t<T, N, void_t<decltype(enable_if_constructible<T>(make_index_sequence<N>()))>>
: std::true_type {};
// Первичный шаблон, объединенный с первым рекурсивным случаем
template <class T, size_t Begin, size_t Middle, class = void >
struct detect_data_member_count : detect_data_member_count<T, Middle, Middle + (Middle - Begin + 1) / 2> {};
// Второй рекурсивный случай, исполненный уже в виде специализации
template <class T, size_t Begin, size_t Middle >
struct detect_data_member_count<T, Begin, Middle, enable_if_t<!enable_if_constructible_t<T, Middle>::value>>
: detect_data_member_count<T, Begin, (Begin + Middle) / 2> {};
// Базовый случай
template <class T, size_t N>
struct detect_data_member_count<T, N, N> {
static constexpr size_t value = N;
};
// API клиента
template <class T>
constexpr size_t data_member_count() {
return detect_data_member_count<T, 0, sizeof(T)>::value;
}
// Проверка
struct our_struct {
int i;
char c;
float f;
double function1(int) {return 42.0; }
std::array<int, 4> arr;
void function2(int);
};
static_assert(data_member_count<our_struct>() == 4);
int main() {}