Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using alias for static member functions?

Tags:

c++

c++11

c++14

Is there a way to alias a static member function in C++? I would like to be able to pull it into scope so that I do not need to fully qualify the name.

Essentially something like:

struct Foo {
  static void bar() {}
};

using baz = Foo::bar; //Does not compile

void test() { baz(); } //Goal is that this should compile

My first thought was to use std::bind (as in auto baz = std::bind(Foo::bar);) or function pointers (as in auto baz = Foo::bar;), but that is unsatisfactory because for each function I want to be able to use the alias in, I need to make a separate variable just for that function, or instead make the alias variable available at global/static scope.

like image 315
Mark Avatar asked Feb 18 '15 03:02

Mark


People also ask

Can static member functions be defined outside of a class?

Static member functions can also be defined outside of the class declaration. This works the same way as for normal member functions. Note that because all the data and functions in this class are static, we don’t need to instantiate an object of the class to make use of its functionality!

How do you call a static member with a type name?

Ordinarily, when you call a static member, you provide the type name along with the member name. Repeatedly entering the same type name to invoke members of the type can result in verbose, obscure code. For example, the following definition of a Circle class references many members of the Math class.

What are function aliases in C++?

Function Aliases In C++ - Fluent C++ Function aliases are a way to use better names in your code, and to have a better decoupling between functionalities. Here is how to achieve this in C++

What is a static data member in C++?

When we define the data member of a class using the static keyword, the data members are called the static data member. A static data member is similar to the static member function because the static data can only be accessed using the static data member or static member function.


1 Answers

using is not the correct tool here. Simply declare your alias (as global if you need to) with auto baz = &Foo::bar.

As suggested in the comments, you can also make it constexpr to have it available, when possible, at compile-time in constant expressions.

struct Foo {
  static void bar() { std::cout << "bar\n"; }
};

constexpr auto baz = &Foo::bar; 

void test() { baz(); }

int main() 
{
    test();
}

Demo

like image 89
quantdev Avatar answered Sep 21 '22 06:09

quantdev