As a rule, code example first:
void f1(int)
{}
#define f2(a) f1(a)
template<class F>
void f3(F f)
{
f(0);
}
int main()
{
f3(f2); // error C2065: 'f2' : undeclared identifier
return 0;
}
Compiled by VC++ 2012.
My question is:
Why does macro expansion follow template expansion? I think it is extremly counter-intuitive and error-prone.
Um, it doesn’t. Macro expansion is done by the preprocessor, template expansion is done by the parser/compiler stage (which runs only after preprocessing).
What you’re missing here is the style of the macro.
f2()is a function-style macro. So if you writef2(without the parentheses), the preprocessor won’t substitute it tof1. If you want such a substitution, simply define it asSide note: as currently standing, this code doesn’t make much sense. Even if you used the parentheses and wrote
f2(), you would get a compiler error, since thef2()macro takes exactly one argument. You should supply an argument to it if it’s a function-style macro that has an argument and is not variadic.