c++aliasmember-functions

How to write a member function alias?


In modern C++ is it possible to write a member function alias with a syntax different from this:

class C {
   int f(int a) { return ++a; }
   inline int g(int a) { return f(a); }
};

I tried in a few ways, none of which work:

class C {
   int f(int a) { return ++a; }
   const auto g1 = f;  // error: 'auto' not allowed in non-static class member
   auto& g2 = f;       // error: 'auto' not allowed in non-static class member
   using g3 = f;       // error: unknown type name 'f'
};

Please, do not suggest to use the preprocessor...

Why do I need this? Because:

P.S.: errors generated by clang 20.1.0


Solution

  • As of today (C++23) there's no solution to have transparent aliases of function or member functions. There is a proposal that adds exactly what you need:

    P0945: Generalizing alias declarations

    But, as far as I know, there has been no recent activity on this proposal.

    The closest you can do today is using a forced inline function:

    class C {
       int f(int a) { return ++a; }
    
       [[clang::always_inline]] // if you use clang
       [[gnu::always_inline]]   // if you use gcc or clang
       __forceinline            // if you use msvc
       int g(int a) { return f(a); }
    };