C++11:如何给函数取别名? [英] C++11: How to alias a function?
问题描述
如果我在命名空间栏中有一个 Foo 类:
If I have a class Foo in namespace bar:
namespace bar
{
class Foo { ... }
};
然后我可以:
using Baz = bar::Foo;
现在就像我在命名空间中定义了名为 Baz 的类一样.
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();
}
然后:
using g = bar::f; // error: ‘f’ in namespace ‘bar’ does not name a type
最干净的方法是什么?
该解决方案也应适用于模板函数.
The solution should also hold for template functions.
定义:如果某个实体 B 是 A 的别名,那么如果 A 的任何或所有用法(当然不是声明或定义)在源代码比(剥离)生成的代码保持不变.例如 typedef A B
是一个别名.#define B A
是一个别名(至少).<代码>T&B = A 不是别名,B 可以有效地实现为间接指针,而未别名"的 A 可以使用立即语义".
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".
推荐答案
您可以使用完美转发定义函数别名(需要一些工作):
You can define a function alias (with some work) using perfect forwarding:
template <typename... Args>
auto g(Args&&... args) -> decltype(f(std::forward<Args>(args)...)) {
return f(std::forward<Args>(args)...);
}
即使 f
重载和/或函数模板,此解决方案也适用.
This solution does apply even if f
is overloaded and/or a function template.
这篇关于C++11:如何给函数取别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!