Function Aliasing in C 11
In C 11, aliasing classes using the using directive is straightforward. However, creating aliases for functions proves more challenging.
Problem:
Consider the following namespace and function declaration:
<code class="cpp">namespace bar { void f(); }</code>
Attempting to alias the function with using g = bar::f; will result in an error, as "f" is not a type in the "bar" namespace.
Clean Solution with Perfect Forwarding:
To create a function alias, perfect forwarding can be used:
<code class="cpp">template<typename... Args> auto g(Args&&... args) -> decltype(f(std::forward<Args>(args)...)) { return f(std::forward<Args>(args)...); }</code>
This solution ensures that g forwards all arguments to f correctly, even if f is overloaded or a function template.
Definition of Alias:
An alias, or B, is an entity of substance A that ensures that any replacement of B in the source code for any usage (not including declarations or definitions) of A will result in unaltered compiled code.
Example:
After defining the g alias, the following code will call f through the alias:
<code class="cpp">g(1, 2, 3); // Calls bar::f(1, 2, 3);</code>
The above is the detailed content of How to Create Function Aliases in C 11?. For more information, please follow other related articles on the PHP Chinese website!