Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c++ - using alias for static member functions?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
"; }
};

constexpr auto baz = &Foo::bar; 

void test() { baz(); }

int main() 
{
    test();
}

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...