[英]Using pointer to member function of a base class on object of derived class
Consider following code snippet: 请考虑以下代码段:
struct Base {
std::string foo () const { std::cout << "Base::foo()\n"; return "X"; }
};
struct Der : Base {};
struct Ptr : std::integral_constant<std::string (Base:: *) () const, &Base::foo> {};
and usage is like this: 和用法是这样的:
Der der;
std::string s = (der.*Ptr::value) ();
std::cout << s << "\n";
Output is as desired: 输出符合要求:
Base::foo()
X
Everything seems to be fine. 一切似乎都很好。
My question is: Is this code correct? 我的问题是:这段代码是否正确? Or am I stepping on the land of undefined behavior?
还是我踩着未定义的行为? Can I use pointer to member function of a base class on object of derived class directly?
我可以直接使用指向派生类对象的基类成员函数的指针吗?
Roughly speaking, the member belongs to the suboject and thus you must use its type to identify it. 粗略地说,该成员属于子对象,因此您必须使用其类型来识别它。 Perfectly fine indeed.
确实非常好。
The other way around doesn't even compile actually: 反过来甚至没有实际编译:
struct Ptr : std::integral_constant<std::string (Der:: *) () const, &Der::foo> {};
The error is pretty clear: 错误很明显:
error: could not convert template argument '&Base::foo' from '[...] (Base:: )() const}' to '[...] (Der:: )() const'
错误:无法将模板参数'&Base :: foo'从'[...](Base :: )()const}'转换为'[...](Der :: )()const'
Where I used [...]
to reduce it a bit. 我使用
[...]
减少它的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.