If I have a class Foo in namespace bar:
namespace bar
{
class Foo { ... }
};
I can then:
using Baz = bar::Foo;
and now it is just like I defined the class in my namespace with the name Baz.
Is it possible to do the same for functions?
namespace bar
{
void f();
}
And then:
using g = bar::f; // error: ‘f’ in namespace ‘bar’ does not name a type
What is the cleanest way to do this?
The solution should also hold for template functions.
Definition: If some entity B is an alias of A, than if any or all usages (not declarations or definitions of course) of A are replaced by B in the source code than the (stripped) generated code remains the same. For example typedef A B
is an alias. #define B A
is an alias (at least). T& B = A
is not an alias, B can effectively implemented as an indirect pointer, wheres an "unaliased" A can use "immediate semantics".
Classes are types, so they can be aliased with
typedef
andusing
(in C++11).Functions are much more like objects, so there's no mechanism to alias them. At best you could use function pointers or function references:
In the same vein, there's no mechanism for aliasing variables (short of through pointers or references).
It's not standard C++, but most compilers provide a way of doing this. With GCC you can do this:
This creates the symbol
f
as an alias for__f
. With VC++ you do the same thing this way:The
constexpr
function pointer can be used as a function alias.In the place where the alias is used the compiler will call the aliased function even when compiling without any optimizations.
With GCC7 the following usage
becomes
The assembly was generated in Compiler Explorer.
You can define a function alias (with some work) using perfect forwarding:
This solution does apply even if
f
is overloaded and/or a function template.It is possible to introduce the function into a different scope without changing its name. So you can alias a function with a different qualified name:
Absolutely:
Try:
A reference is an alias to an existing object.
I just created a reference to a function. The reference can be used in exactly the same way as the original object.