Reputation: 9527
This may be silly question, but just of curiosity, I wanted to know if something like it is possible.
Lets say I have function
void Foo(int a)
{
...
}
And I want to do something like this
@pragma mypragma
void Foo(int a)
{
...
}
and at compile time I want to generate this (if pragma mypragma
is defined before function)
void Foo(void * ptr, int a)
{
Foo(a);
}
void Foo(int a)
{
...
}
Or with return value
int Foo(void * ptr, int a)
{
return Foo(a);
}
int Foo(int a)
{
...
}
EDIT: Some example. What I want is similar to OpenMP
Upvotes: 3
Views: 759
Reputation: 40625
Of course, you can use the C preprocessor for this as David suggests, but when you have more complex tasks at hand, you should think about other tools to generate the code you need.
Examples of such preprocessors I have seen in use include m4
and python
.
python
seems to be more suited to the syntax you are envisioning, however, you cannot execute it as a preprocessor, you have to run a python program on your file to generate the desired output.
m4
, on the other hand is a real preprocessor, meaning that you basically feed your source file directly into m4
, just like your compiler feeds C files through the C preprocessor. Its syntax is very functional in style, which may be good or bad depending on what you want to achieve.
Upvotes: 0
Reputation: 27864
I think something like this will work for you. You'll need individual macros for returning a value vs. not, and for each possible number of parameters.
// pt<x>: Parameter type <x>
// pn<x>: Parameter name <x>
#define METHOD_PAIR1(name, pt1, pn1) \
void name(pt1 pn1); \
void name(void* ptr, pt1 pn1) { name(pn1); } \
void name(pt1 pn1)
#define METHOD_PAIR2(name, pt1, pn1, pt2, pn2) \
void name(pt1 pn1, pt2 pn2); \
void name(void* ptr, pt1 pn1, pt2 pn2) { name(pn1, pn2); } \
void name(pt1 pn1, pt2 pn2)
#define FUNCTION_PAIR1(ret, name, pt1, pn1) \
ret name(pt1 pn1); \
ret name(void* ptr, pt1 pn1) { return name(pn1); } \
ret name(pt1 pn1)
#define FUNCTION_PAIR2(ret, name, pt1, pn1, pt2, pn2) \
ret name(pt1 pn1, pt2 pn2); \
ret name(void* ptr, pt1 pn1, pt2 pn2) { return name(pn1, pn2); } \
ret name(pt1 pn1, pt2 pn2)
METHOD_PAIR1(Foo, int, a)
{
// Insert body of void Foo(int a) here.
}
FUNCTION_PAIR1(int, Foo2, int, a)
{
// Insert body of int Foo2(int a) here.
}
Upvotes: 2