[英]Cast one pointer-to-member-function to another of same class
使用reinterpret_cast
将指向成员函数的指针reinterpret_cast
为同一个类的另一个指向成员函数是否合法? 以下示例有效。 但这是合法的吗?
#include<iostream>
#include<vector>
#include<string>
class A
{
public:
void func_int(int x) { std::cout << x << std::endl; }
void func_string(std::string const& x) { std::cout << x << std::endl; }
};
int main()
{
std::vector<void(A::*)()> v;
v.push_back(reinterpret_cast<void(A::*)()>(&A::func_int));
v.push_back(reinterpret_cast<void(A::*)()>(&A::func_string));
A a;
(a.*reinterpret_cast<void(A::*)(int)>(v[0]))(5);
(a.*reinterpret_cast<void(A::*)(std::string const&)>(v[1]))(std::string{"Test"});
return 0;
}
在[expr.reinterpret.cast] ,C ++草案指出:
如果
T1
和T2
都是函数类型或两种对象类型,则可以将类型为“T1
类型X
的成员的指针”的prvalue显式转换为不同类型的prvalue“指向类型为T2
的Y
的成员的指针”。 72空成员指针值( [conv.mem] )将转换为目标类型的空成员指针值。 除以下情况外,此转换的结果未指定:
将“指向成员函数的指针”类型的prvalue转换为指向成员函数类型的不同指针,并返回其原始类型,从而生成指向成员值的原始指针。
类型的prvalue转换“指针的数据成员
X
型的T1
”的类型“指针的数据成员Y
类型的T2
”(其中的对准要求T2
并不比那些更严格的T1
),并返回到其原始type产生指向成员值的原始指针。
72)
T1
和T2
可能具有不同的cv-限定符 ,受限于reinterpret_cast
不能丢弃const的总体限制。
由于您将“指向成员函数的指针”转换为另一个“指向成员函数的指针”类型并返回,因此它会生成原始值。 这是合法且定义明确的行为。 所以你的代码应该正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.