First, there are a lot of posts on overloading macros:
- Can macros be overloaded by number of arguments?
- C Overloading Macros
- Macro overloading
- Overloading Macro on Number of Arguments
- etc. ...
However, all of them ask the question about variadic macros.
What I'd like to ask is if the following is possible:
#define FOO 3
#define FOO(a,b) a b
int main() {
int a = FOO(0,1);
int b = FOO;
std::cout << a b;
return 0;
}
I'd like for it to work on clang
as well.
CodePudding user response:
No, macros aren't that clever. They are a simple text substitution, performed by the pre-processor.
At the expense of one more set of brackets you can overload functions though, something like:
int foo () { return 3; }
int foo (int a, int b) { return a b; }
int main ()
{
int a = foo (0, 1);
int b = foo ();
}
And if you want your foo
s to work with a wider set of types, make them templates.
CodePudding user response:
It's not a macro, but looks like it
struct SmartMacro {
constexpr operator int() const noexcept { return 3; }
constexpr int operator()(int a, int b) const noexcept { return a b; }
};
constexpr SmartMacro FOO;
int main() {
int a = FOO(0,1);
int b = FOO;
std::cout << a b;
return 0;
}