Welcome to OGeek 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...