Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: How to alias a function? [duplicate]

Tags:

c++

linux

gcc

c++11

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

like image 963
Andrew Tomazos Avatar asked Mar 25 '12 21:03

Andrew Tomazos


2 Answers

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.

like image 166
Jeremiah Willcock Avatar answered Sep 29 '22 10:09

Jeremiah Willcock


The constexpr function pointer can be used as a function alias.

namespace bar {     int f(); }  constexpr auto g = bar::f; 

It is highly likely (but not guaranteed by the language) that using g uses bar::f directly. Specifically, this depends on compiler version and optimization level.

In particular, this is the case for:

  • GCC 4.7.1+, without optimization,
  • Clang 3.1+, without optimization,
  • MSVC 19.14+, with optimization.

See assembly generated by these compilers.

like image 24
Paweł Bylica Avatar answered Sep 29 '22 12:09

Paweł Bylica