使用别名的静态成员函数? [英] using alias for static member functions?
问题描述
在C ++中是否有别名别名静态成员函数的方法?我希望能够将其应用到范围内,这样就不必完全限定名称。
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.
本质上类似于:
struct Foo {
static void bar() {}
};
using baz = Foo::bar; //Does not compile
void test() { baz(); } //Goal is that this should compile
我的第一个想法是使用 std :: bind
(如 auto baz = std :: bind(Foo :: bar);
)或函数指针(如 auto baz = Foo :: bar;
),但这并不令人满意,因为对于每个要使用别名的函数,我都需要为此单独创建一个变量函数,或者使别名变量在全局/静态范围内可用。
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.
推荐答案
使用
不是此处的正确工具。只需使用 auto baz =& Foo :: bar
声明您的别名(如果需要,可以声明为全局别名)。
using
is not the correct tool here. Simply declare your alias (as global if you need to) with auto baz = &Foo::bar
.
根据注释中的建议,也可以使 constexpr
尽可能在编译时以常量表达式提供它。
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
这篇关于使用别名的静态成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!