是否有适用于方法的 offsetof 版本?
Is there a version of offsetof that applies to methods?
给定结构:
struct Struct {
int _a;
int a () { return _a; }
};
可以得到 _a
与 offsetof( Struct, _a )
的偏移量。
我将如何为 &Struct::a
之类的东西做同样的事情?
引自cppreference.com's page on the offsetof
macro:(强调我的)
Given an object o
of type type
and static storage duration, o.member
shall be an lvalue constant expression that refers to a subobject of o
. Otherwise, the behavior is undefined. Particularly, if member is a static data member, a bit-field, or a member function, the behavior is undefined.
How would I go about doing the same for something like &Struct::a?
你不会也不能为成员函数做这样的事情,因为“偏移量”的概念对于成员函数没有意义。成员函数不像非静态成员变量那样存储在 class 实例中。
您似乎在寻找 pointers to members 函数:
int Struct::*m = &Struct::_a;
int (Struct::*f)() = &Struct::a;
用法类似于
Struct s;
s.*m = 42;
std::cout << (s.*f)() << std::endl;
给定结构:
struct Struct {
int _a;
int a () { return _a; }
};
可以得到 _a
与 offsetof( Struct, _a )
的偏移量。
我将如何为 &Struct::a
之类的东西做同样的事情?
引自cppreference.com's page on the offsetof
macro:(强调我的)
Given an object
o
of typetype
and static storage duration,o.member
shall be an lvalue constant expression that refers to a subobject ofo
. Otherwise, the behavior is undefined. Particularly, if member is a static data member, a bit-field, or a member function, the behavior is undefined.
How would I go about doing the same for something like &Struct::a?
你不会也不能为成员函数做这样的事情,因为“偏移量”的概念对于成员函数没有意义。成员函数不像非静态成员变量那样存储在 class 实例中。
您似乎在寻找 pointers to members 函数:
int Struct::*m = &Struct::_a;
int (Struct::*f)() = &Struct::a;
用法类似于
Struct s;
s.*m = 42;
std::cout << (s.*f)() << std::endl;