[英]Initialization of std::array with function pointer member function of constexpr object
I am trying to initialize an std::array of function pointers. 我正在尝试初始化一个std ::数组函数指针。 These pointers point to member functions of an already instantiated object. 这些指针指向已实例化对象的成员函数。
Can somebody please help with the following example? 有人可以帮助以下示例吗? Many thanks in advance! 提前谢谢了!
#include <array>
using TVoidVoid = void (*)(void);
class Foo {
public:
constexpr Foo() {}
void myHandler() {}
};
class Bar {
public:
constexpr Bar() : handler_{nullptr} {}
constexpr Bar(TVoidVoid handler) : handler_{handler} {}
private:
TVoidVoid handler_;
};
Foo f;
std::array<Bar, 5> bar_array = {{Bar{}, Bar{f.myHandler}}};
int main() {}
compiling produces: 编译产生:
main.cpp:22:56: error: no matching function for call to ‘Bar::Bar(<brace-enclosed initializer list>)’
std::array<Bar, 5> bar_array = {{Bar{}, Bar{f.myHandler}}};
I am using g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
. 我使用的是g++ (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0
。
Pointers to free functions are handled differently than pointers to member functions. 指向自由函数的指针的处理方式与指向成员函数的指针不同。 The TVoidVoid
type is a pointer to a free function, but you need a pointer to a Foo
member function. TVoidVoid
类型是指向自由函数的指针,但是您需要一个指向Foo
成员函数的指针。 Hence, define Foo
first, 因此,首先定义Foo
,
class Foo { /* As before... */ };
then go with a type alias for the member function ( Foo
must be known at this point) 然后使用成员函数的类型别名(此时必须知道Foo
)
// Note the different syntax to the former TVoidVoid
using FooVoidVoid = void (Foo::*)();
Next, Bar
must be adjusted such that its data member is of type FooVoidVoid
and the constructor accepts this type as an argument (the rest of Bar
can be left as it is), and finally defined the array as 接下来,必须调整Bar
,使其数据成员的类型为FooVoidVoid
,构造函数接受此类型作为参数( Bar
的其余部分可以保留原样),最后将数组定义为
std::array<Bar, 3> bar_array = {{Bar{}, Bar{&Foo::myHandler}}};
Note that &Foo::myHandler
has nothing to do with any existing Foo
instance. 请注意, &Foo::myHandler
与任何现有的Foo
实例无关。 It's just a pointer to a Foo
member function, and only when you invoke it, this must be brought together with a Foo
object (the special operators .*
and ->*
are meant for this to happen, or use std::invoke
once you upgrade to a C++17-enabled compiler). 它只是一个指向Foo
成员函数的指针,只有当你调用它时,才必须将它与Foo
对象放在一起(特殊运算符.*
和->*
意味着要发生这种情况,或者使用std::invoke
您升级到启用C ++ 17的编译器)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.