C ++ 11:如何别名函数? [英] C++11: How to alias a function?

查看:1528
本文介绍了C ++ 11:如何别名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在命名空间栏中有Foo类:

 命名空间bar 
{
class Foo {...}
};

我可以:

 使用Baz = bar :: Foo; 

现在它就像我在名称空间中定义名称为Baz的类。



是否可以对函数执行相同操作?

 命名空间bar 
{
void f();
}

然后:

 使用g = bar :: f; //错误:'f'在命名空间'bar'中没有命名类型



定义:

/ strong>如果某个实体B是A的别名,则比在源代码中A的任何或所有用法(不是声明或定义)被B代替,而不是(剥离)生成的代码保持不变。例如 typedef A B 是别名。 #define B A 是一个别名(至少)。 T& B = A 不是别名,B可以有​​效地实现为间接指针,而未定义A可以使用立即语义。

解决方案

您可以使用完美转发来定义函数别名(使用某些工作):

  template< typename ... Args> 
auto g(Args& ... args) - > decltype(f(std :: forward< Args>(args)...)){
return f(std :: forward&
}

此解决方案即使 f 是重载的和/或函数模板。


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".

解决方案

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)...);
}

This solution does apply even if f is overloaded and/or a function template.

这篇关于C ++ 11:如何别名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆