-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate_struct_with_static_func.cpp
61 lines (48 loc) · 1.71 KB
/
template_struct_with_static_func.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
#include <iostream>
#include <optional>
typedef bool lua_State;
lua_State* lua_state = new lua_State;
bool lua_isinteger(lua_State* state, int idx) { return true; }
int lua_tointeger(lua_State* state, int idx) { return 42; }
bool lua_isstring(lua_State* state, int idx) { return true; }
char* lua_tostring(lua_State* state, int idx) { return (char*)"asd"; }
// стало:
template<typename T>
struct type_name
{
static auto get_value()
{
throw "Invalid type for struct 'type_name'";
}
};
#define GENERATE_TYPENAME(type, predicate, getter) \
template<> \
struct type_name<type> \
{ \
static auto get_value() \
{ \
std::optional<type> value; \
\
if (predicate(lua_state, -1)) \
{ \
value = (type)getter(lua_state, -1); \
} \
\
return value; \
} \
}; \
GENERATE_TYPENAME(int, lua_isinteger, lua_tointeger);
GENERATE_TYPENAME(char*, lua_isstring, lua_tostring);
template<typename T>
std::optional<T> readValue()
{
return type_name<T>::get_value();
}
int main()
{
std::cout << *readValue<int>() << std::endl;
std::cout << *readValue<char*>() << std::endl;
std::cout << std::endl;
delete lua_state;
return 0;
}