I am asking about a way to improve code readability
I was able to make a macro like this for a small library I'm making
#define fun(name, arg1, arg2) void name(int arg1, int arg2)
NOTE: int is an existent class, but I replace it with int so anyone can run it
This would allow me to use this code to create a function:
fun(testFunction, x, y) {
// do stuff
std::cout << x << y << std::endl;
}
and then in my main:
int main() {
testFunction(1, 2);
return 0;
}
This works great (at least in Visual Studio, haven't tested in GCC but I think it works there too).
Is it possible to make a macro that would be like:
#define fun name(arg1, arg2) void name(int arg1, int arg2)
so a macro that would allow me to declare a function like:
fun testFunction(x, y) {
// do stuff
}
The actual thing I am asking if is there a way to make a macro that allows me to do this (for example)
CustomClassTemplate doStuff(CustomClass& arg1, CustomClassTemplate arg2, Library::Binary::Binary bin) {
// do stuff
return CustomClassTemplate(/*blah, blah, blah*/);
}
to this:
fun doStuff(arg1, arg2, bin) {
// do stuff
return CustomClassTemplate(/* blah blah blah*/);
}
you can create an empty class for each argument
CodePudding user response:
As you already discovered: technically it can be done, but not in a #define fun name(arg1, arg2)
and I think that's a good thing because you want to hide the fact that you're using macros while that should be clear enough. Also fun doStuff(arg1, arg2, bin)
looks like a regular function declaration with empty parameter types (no parameter names) and returning fun
.
What you already saw in the comments is that a lot of people don't agree that that using macros is a good thing and that will also be true for the people who will use your library or work on it, so you might take that into account when deciding to use it anyway.
Other points to take into account:
- copying and adapting code lines isn't that costly
- you can align the parameters to show that they're the same
- variations in function declarations will need more macros and longer names
- problems in functions with parameters are easier spotted when they are explicit