[英]Wrapping functions using C macros (with renaming)
I am trying to define a function using macros that would actually wrap an existing function into an other one with a prefix. 我正在尝试使用宏定义一个函数,该宏实际上会将现有函数包装到带有前缀的另一个函数中。 Let's say for example:
举例来说:
int f1(int a, void *b, char c) { return 1; }
int f2(void *a) { return 1; }
void f3(void *a, int b) {}
void f4() {}
#define WRAP(prefix, f) // do something
WRAP(a, f1) or WRAP(a,f1,int,void*,char) or WRAP(a,f1,int,a,void*,b,char,c)
This should produce something like: 这应该产生类似以下内容:
int a_f1(int a, void *b, char c);
int a_f1(int a, void *b, char c) { return f1(a,b,c); }
I'm trying to do it so it could work with any of f1, f2, f3 or f4. 我正在尝试这样做,以便它可以与f1,f2,f3或f4一起使用。 If anyone has an idea on how to do that I would be really thanksfull.
如果有人对如何做有任何想法,我将非常感谢。
If you can be bothered to specify the return type and parameters of the wrapped function, Boost.Preprocessor has you covered: 如果可以麻烦指定包装函数的返回类型和参数,Boost.Preprocessor可以解决:
#include <boost/preprocessor/tuple/to_seq.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/comma_if.hpp>
#define WRAP_declare_param(r, data, i, paramType) \
BOOST_PP_COMMA_IF(i) paramType _ ## i
#define WRAP_forward_param(r, data, i, paramType) \
BOOST_PP_COMMA_IF(i) _ ## i
#define WRAP_seq(prefix, retType, function, argSeq) \
inline retType prefix ## function ( \
BOOST_PP_SEQ_FOR_EACH_I(WRAP_declare_param, ~, argSeq) \
) { \
return function( \
BOOST_PP_SEQ_FOR_EACH_I(WRAP_forward_param, ~, argSeq) \
); \
}
#define WRAP(prefix, retType, function, ...) \
WRAP_seq(prefix, retType, function, BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)))
Which lets you write the following: 通过它可以编写以下内容:
// Declared somewhere...
int foo(float, double);
WRAP(p_, int, foo, float, double)
// ^^ Prefix
// ^^^ Return type
// ^^^ Function
// ^^^^^^^^^^^^^ Parameter types
Which expands to: 扩展为:
inline int p_foo ( float _0 , double _1 ) { return foo( _0 , _1 ); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.