It's easy to create a new name for a type, a variable or a namespace. But how do I assign a new name to a function? For example, I want to use the name holler
for printf
. #define is obvious... any other way?
Solutions:
#define holler printf
void (*p)() = fn; //function pointer
void (&r)() = fn; //function reference
inline void g(){ f(); }
Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed.
Type alias is a name that refers to a previously defined type (similar to typedef). Alias template is a name that refers to a family of types.
You can define your own alias method by adding the statement a = b to your class definition. This creates an alias method a() for the original method b() .
You can use an alias declaration to declare a name to use as a synonym for a previously declared type. (This mechanism is also referred to informally as a type alias). You can also use this mechanism to create an alias template, which can be useful for custom allocators.
There are different approaches:
With C++11 with non-template non-overloaded functions you can simply use:
const auto& new_fn_name = old_fn_name;
If this function has multiple overloads you should use static_cast
:
const auto& new_fn_name = static_cast<OVERLOADED_FN_TYPE>(old_fn_name);
Example: there are two overloads of function std::stoi
int stoi (const string&, size_t*, int); int stoi (const wstring&, size_t*, int);
If you want to make an alias to the first version you should use the following:
const auto& new_fn_name = static_cast<int(*)(const string&, size_t*, int)>(std::stoi);
Note: there is no way to make an alias to overloaded function such that all its overloaded versions work, so you should always specify which exact function overload you want.
With C++14 you can go even further with constexpr
template variables. That allows you to alias templated functions:
template<typename T> constexpr void old_function(/* args */); template<typename T> constexpr auto alias_to_old = old_function<T>;
Moreover, starting with C++11 you have a function called std::mem_fn
that allows to alias member functions. See the following example:
struct A { void f(int i) { std::cout << "Argument: " << i << '\n'; } }; A a; auto greet = std::mem_fn(&A::f); // alias to member function // prints "Argument: 5" greet(a, 5); // you should provide an object each time you use this alias // if you want to bind an object permanently use `std::bind` greet_a = std::bind(greet, a, std::placeholders::_1); greet_a(3); // equivalent to greet(a, 3) => a.f(3);
You can create a function pointer or a function reference:
void fn() { } //... void (*p)() = fn;//function pointer void (&r)() = fn;//function reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With