c++模板实现多参数任意传 - 方法实现

游戏中lua脚本中,如果实现了c++调用lua脚本时参数任意传,那真的是爽的一逼。这个是从《c++ primer plua 6th》中看到的,是以方法实现的递归,在另一本书《modern c++ design》中,使用的更高级,是以类的继承实现递归,后面的文章中将会贴出。

利用c++的模板,自己在定个数据结构,重载多个方法去实现不同参数的匹配,装到自己定的数据结构中,最后在对lua的压栈过程中压如不同的参数类型中。

对于自定义类的传入,涉及的代码有点小多,所以这里只贴了基础数据的多参数。自定义类的话有空补上

下面上代码:

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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

enum LuaParameterType
{
LPT_NUM = 0,
LPT_STR,
LPT_BOOL,
LPT_CUSTOM,
LPT_COUNT,
};
struct LuaParameter
{
LuaParameterType type; //类型
void* value; //自定义类型值
double num; //number
bool b; //bool
std::string str; //字符串类型
std::string typeName; //在类型为自定义类型时有效
std::string name; //预设时用到这个数据
};


std::vector<LuaParameter> mutipleArgsVec;
void insertArg(bool _b)
{
LuaParameter para;
para.type = LPT_BOOL;
para.b = _b;
mutipleArgsVec.push_back(para);
}
void insertArg(char _c)
{
LuaParameter para;
para.type = LPT_STR;
char tmp[2] = { _c, '\0' };
para.str = std::string(tmp);
mutipleArgsVec.push_back(para);
}
void insertArg(const char* _str)
{
LuaParameter para;
para.type = LPT_STR;
para.str = std::string(_str);
mutipleArgsVec.push_back(para);
}
void insertArg(std::string _str)
{
LuaParameter para;
para.type = LPT_STR;
para.str = std::string(_str);
mutipleArgsVec.push_back(para);
}
void insertArg(int _num)
{
LuaParameter para;
para.type = LPT_NUM;
para.num = _num;
mutipleArgsVec.push_back(para);
}
void insertArg(float _num)
{
LuaParameter para;
para.type = LPT_NUM;
para.num = _num;
mutipleArgsVec.push_back(para);
}

void printData()
{
for (LuaParameter para : mutipleArgsVec)
{
if (para.type == LPT_NUM)
{
printf("--- is number:%lf\n", para.num);
}
else if (para.type == LPT_STR)
{
printf("--- is string:%s\n", para.str.c_str());
}
else if (para.type == LPT_BOOL)
{
printf("--- is bool:%d\n", (int)para.b);
}
}
}

//--------------------- 实现模板的递归 begin ------------------
//definition for 0 parameters -- 无参数时,最后一次递归时会调用,停止递归,实现为空即可
void showArgs() {}

//definition for 1 or more parameters -- 有参数是调用这个函数
template < typename T, typename... Args>
void showArgs(T value, Args... args)
{
insertArg(value);
showArgs(args...);
}
//--------------------- 实现模板的递归 end ------------------

void testArgs()
{
mutipleArgsVec.clear();
showArgs(123, "aaa", 23.23f, 'c', true);
printData();
}