| 1 |
/* { dg-do run } */ |
| 2 |
/* { dg-additional-options "-fstrict-aliasing" } */ |
| 3 |
/* { dg-skip-if "requires hosted libstdc++ for cstdlib size_t" { ! hostedlib } } */ |
| 4 |
|
| 5 |
#include <cstdlib> |
| 6 |
#include <array> |
| 7 |
#include <type_traits> |
| 8 |
|
| 9 |
template <typename T1, typename T2> |
| 10 |
struct variant |
| 11 |
{ |
| 12 |
constexpr variant(T1 arg) |
| 13 |
: f1(arg), |
| 14 |
index(0) |
| 15 |
{} |
| 16 |
|
| 17 |
constexpr variant(T2 arg) |
| 18 |
: f2(arg), |
| 19 |
index(1) |
| 20 |
{} |
| 21 |
|
| 22 |
union |
| 23 |
{ |
| 24 |
T1 f1; |
| 25 |
T2 f2; |
| 26 |
}; |
| 27 |
std::size_t index = 0; |
| 28 |
}; |
| 29 |
|
| 30 |
template <typename T1, typename T2> |
| 31 |
constexpr const T1* get_if(const variant<T1, T2>* v) |
| 32 |
{ |
| 33 |
if (v->index != 0) |
| 34 |
{ |
| 35 |
return nullptr; |
| 36 |
} |
| 37 |
return &v->f1; |
| 38 |
} |
| 39 |
|
| 40 |
template <typename T2, typename T1> |
| 41 |
constexpr const T2* get_if(const variant<T1, T2>* v) |
| 42 |
{ |
| 43 |
if (v->index != 1) |
| 44 |
{ |
| 45 |
return nullptr; |
| 46 |
} |
| 47 |
return &v->f2; |
| 48 |
} |
| 49 |
|
| 50 |
template <typename T, size_t N> |
| 51 |
struct my_array |
| 52 |
{ |
| 53 |
constexpr const T* begin() const |
| 54 |
{ |
| 55 |
return data; |
| 56 |
} |
| 57 |
|
| 58 |
constexpr const T* end() const |
| 59 |
{ |
| 60 |
return data + N; |
| 61 |
} |
| 62 |
|
| 63 |
T data[N]; |
| 64 |
}; |
| 65 |
|
| 66 |
template <typename ...Ts> |
| 67 |
constexpr auto get_array_of_variants(Ts ...ptrs) |
| 68 |
{ |
| 69 |
return std::array<variant<std::decay_t<Ts>...>, sizeof...(Ts)>{ ptrs... }; |
| 70 |
} |
| 71 |
|
| 72 |
template <typename T> |
| 73 |
constexpr auto get_member_functions(); |
| 74 |
|
| 75 |
template <typename Member, typename Class> |
| 76 |
constexpr int getFuncId(Member (Class::*memFuncPtr)) |
| 77 |
{ |
| 78 |
int idx = 0u; |
| 79 |
for (auto &anyFunc : get_member_functions<Class>()) |
| 80 |
{ |
| 81 |
if (auto *specificFunc = get_if<Member (Class::*)>(&anyFunc)) |
| 82 |
{ |
| 83 |
if (*specificFunc == memFuncPtr) |
| 84 |
{ |
| 85 |
return idx; |
| 86 |
} |
| 87 |
} |
| 88 |
++idx; |
| 89 |
} |
| 90 |
std::abort(); |
| 91 |
} |
| 92 |
|
| 93 |
struct MyStruct |
| 94 |
{ |
| 95 |
void fun1(int /*a*/) {} |
| 96 |
|
| 97 |
int fun2(char /*b*/, short /*c*/, bool /*d*/) { return 0; } |
| 98 |
|
| 99 |
}; |
| 100 |
|
| 101 |
template <> |
| 102 |
constexpr auto get_member_functions<MyStruct>() |
| 103 |
{ |
| 104 |
return get_array_of_variants(&MyStruct::fun1, &MyStruct::fun2); |
| 105 |
} |
| 106 |
|
| 107 |
int main() |
| 108 |
{ |
| 109 |
return getFuncId(&MyStruct::fun1); |
| 110 |
} |