[英]C++ inline initialize static function member
I want to implement a member function as follows:我想实现一个成员 function 如下:
void X() {}
class Foo
{
static void(*Bar)() = X;
};
This does not compile:这不编译:
error: 'constexpr' needed for in-class initialization of static data member 'void (* Foo::Bar)()' of non-integral type
错误:非整数类型的 static 数据成员“void (* Foo::Bar)()”的类内初始化需要“constexpr”
I know this is not legal.我知道这是不合法的。 I have to either initialize Bar outside of the class scope or make it "inline static".
我必须在 class scope 之外初始化 Bar 或使其成为“内联静态”。 The problem is that the latter is a C++17 feature and I must do with C++11 (BCC32X limitations).
问题是后者是 C++17 功能,我必须使用 C++11(BCC32X 限制)。 So my question is: Is there a way to do this on the same line?
所以我的问题是:有没有办法在同一条线上做到这一点? Maybe making it const?
也许让它成为常量? I know we can do this( Source )...
我知道我们可以做到这一点( 来源)...
class Foo
{
static int const i = 42;
}
But can we apply it to functions somehow?但是我们能以某种方式将它应用于函数吗?
PD: I know there are infinite solutions to my question all over SO, but up until now all I've seen end up relying on later C++ features not available to me. PD:我知道我的问题有无数种解决方案,但到目前为止,我所看到的一切最终都依赖于我无法使用的后来的 C++ 功能。
Since C++11 you can use constexpr
to initialize static members of non-integral/enumeration types in the class declaration.从 C++11 开始,您可以使用
constexpr
在 class 声明中初始化 static 非整数/枚举类型的成员。
As @paddy comments below, this makes Bar
const so it would only be a viable solution if you don't plan to modify it, what you are not doing in the question's code.正如下面的@paddy 评论,这使
Bar
成为常量,因此只有在您不打算修改它(您在问题代码中没有做的事情)的情况下,它才是一个可行的解决方案。
#include <iostream> // cout
void X() {
std::cout << "Blah\n";
}
struct Foo {
static constexpr void(*Bar)() = X;
};
int main() {
Foo::Bar();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.