使用C宏包装函数(带有重命名) [英] Wrapping functions using C macros (with renaming)
本文介绍了使用C宏包装函数(带有重命名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用宏定义一个函数,该宏实际上会将现有函数包装到带有前缀的另一个函数中. 举例来说:
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); }
我正在尝试这样做,以便它可以与f1,f2,f3或f4中的任何一个一起使用. 如果有人对如何做有任何想法,我将非常感谢.
I'm trying to do it so it could work with any of f1, f2, f3 or f4. If anyone has an idea on how to do that I would be really thanksfull.
推荐答案
如果您不愿意指定包装函数的返回类型和参数,Boost.Preprocessor将为您服务:
If you can be bothered to specify the return type and parameters of the wrapped function, Boost.Preprocessor has you covered:
#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
其中扩展到:
inline int p_foo ( float _0 , double _1 ) { return foo( _0 , _1 ); }
这篇关于使用C宏包装函数(带有重命名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文