@c++17 实现反射
http 服务器 需求 通过url及参数解析出 命名空间/类/方法?参数
例子: post
http://127.0.0.1/home/index
参数
name=xxx&age=xxx
对应类
class home
{
public:
std::string index(std::string name,int age)
{
return “年龄:”+std::to_string(age)+" 名称:"+name;
}
std::string login(std::shared_ptr<user_info> user, int count)
{
return “”;
}
}
实现动态创建并调用 TestClass::func 方法
采用侵入式 反射
实现调用例子 http服务(asio2)
class home: public utility:reflect
{
public:
home()
{
REFLECT_CLASS(home);
REFLECT_METHOD(&home::func, “name”,“age”);
}
std::string index(std::string name,int age)
{
return "年龄:"+std::to_string(age)+" 名称:"+name;
}
std::string login(std::shared_ptr<user_info> user, int count)
{
return "";
}
//单例
static utility::reflect * instance()
{
static std::shared_ptr<utility::reflect> _instance(new TestClass );
return _instance.get();
}
}
REFLECT_SINGLE_REGISTER(home);
asio2
接收请求
解析url
生成调用参数
/home/index?name=xxx&age=xxx
解析类名 home
动态创建类
utility::reflect * obj = utility::reflect::resolve(“home”);
解析方法名称 index
std::mapstd::string,std::any params;
params[“name”]=std::string(“xxx”);
params[“age”]= int(10);
std::any result = obj->invoke(“index”,params);
动态调用完成
后续 讲解实现