It just recently came to my attention that there are probably a lot of C++ programmers out there that don't know about function references. People discuss function pointers from time to time, but almost never discuss function referencs. It's hard to find any info about them on the web too.
I've actually been using them for a few years now.
Example usage:
typedef int Func(int x);
int bar2(int x) { return x*2; }
int bar3(int x) { return x*3; }
void foo(Func &foobar)
{
std::cout << foobar(5);
}
int main()
{
foo(bar2);
foo(bar3);
}
As you can see, they are actually cleaner to use than function pointers! Also, just like the difference between regular pointers and references, function references can't be made to point to a different function, and can't be NULL. Surely they'd thererfore allow for more optimisation possibilities?
The only thing that isn't the same as regular references is that there's no usefulness to making them const. i.e.
void foo(const Func &foobar)
Such code causes the following in VS2008:
warning C4180: qualifier applied to function type has no meaning; ignored
Does anyone have any thoughts as to why they might not be very popular?
Should we actually be preferring these over function pointers for the same reasons that we should prefer regular references over pointers?
Do they work equally as well on all compilers?