【发布时间】:2013-08-22 04:47:17
【问题描述】:
是否可以生成方法定义(具有确切数量的参数和已知类型的返回值),具有:
- 在可变参数包中“冻结”的方法参数类型
- 推导方法返回类型
- 方法名称(传递给宏?)
详情:
我有一个简单的反射结构(为了便于阅读,省略了部分特化的东西),它推导出成员函数的返回类型和参数类型:
template<typename RetType, typename ...ArgTypes>
struct reflect_method<RetType(HostClassType::*)(ArgTypes...)> {
using method_type = RetType;
using method_args = type_placeholder<ArgTypes...>;
using call_type = RetType(HostClassType::*)(ArgTypes...);
};
其中method_type 是方法返回类型,method_args 是在帮助程序模板结构type_placeholder 中“冻结”的方法参数类型。
我要做的是在生成的类中创建一个方法,该方法将反映参数并返回其他类的另一个方法的类型。创建的方法将为反射方法提供装饰。
伪代码实现:
#define RPCCLASS(class_name) class RPC##class_name : public class_name \
{ \
using SelfType = RPC##class_name; \
using ParentType = class_name;
#define RPCCLASS_END() };
#define RPCBIND(method_name) \
using method_name_##tag = reflect_method<decltype(ParentType::method_name)>; \
method_name_##tag::method_type
method_name(method_name_##tag::method_args::at<0>::type arg0, \
method_name_##tag::method_args::at<1>::type arg1, \
/* ... */ \
/*don't know how to put correct number of arguments here)*/) \
{ \
/* do some stuff */ \
/* ... */ \
/* invoke the reflected method */ \
return Invoke<method_name_##tag>::apply(this, method_name, \
arg0, \
arg1 \
/*again don't know how to put correct number of arguments here)*/) \
}
// USAGE:
class MyOwnClass {
public:
virtual long long doFun(int a, char b, const std::string& c);
};
RPCCLASS(MyOwnClass)
RPCBIND(doFun)
RPCCLASS_END()
【问题讨论】:
-
你可能想看看Turtle.Mocks模拟对象框架的实现。他们的
MOCK_METHOD宏中有类似的东西 -
谢谢,我会调查一下
-
如果你会使用 c++11 不应该
decltype帮助你很多吗? -
@Alex 我需要使用 C++11 :) decltype 允许您检查方法签名,我需要的是相反的。拥有一个函数签名,我想生成一个类似的函数(仅更改函数名称)。示例:从“int original(float, char)”我想得到“int producer_from_original(float, char)”
标签: c++ metaprogramming template-meta-programming