如何在 C++ 中为函数名分配别名? [英] How do I assign an alias to a function name in C++?
问题描述
为类型、变量或命名空间创建新名称很容易.但是如何为函数分配一个新名称呢?例如,我想对 printf
使用名称 holler
.#define 很明显...还有其他方式吗?
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?
解决方案:
#define holler printf
void (*p)() = fn;//函数指针
void (&r)() = fn;//函数参考
inline void g(){ f();}
推荐答案
有不同的方法:
使用带有非模板非重载函数的 C++11,您可以简单地使用:
With C++11 with non-template non-overloaded functions you can simply use:
const auto& new_fn_name = old_fn_name;
如果这个函数有多个重载,你应该使用static_cast
:
const auto& new_fn_name = static_cast<OVERLOADED_FN_TYPE>(old_fn_name);
示例:函数 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.
使用 C++14,您可以使用 constexpr
模板变量走得更远.这允许您为模板化函数设置别名:
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>;
此外,从 C++11 开始,您有一个名为 std::mem_fn
的函数,它允许为成员函数设置别名.请参见以下示例:
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 << '
';
}
};
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);
这篇关于如何在 C++ 中为函数名分配别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!