[英]Cast one pointer-to-member-function to another of same class
Is it legal to cast a pointer-to-member-function to another pointer-to-member-function of the same class using reinterpret_cast
? 使用
reinterpret_cast
将指向成员函数的指针reinterpret_cast
为同一个类的另一个指向成员函数是否合法? The following example works. 以下示例有效。 But is it legal?
但这是合法的吗?
#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;
}
At [expr.reinterpret.cast] the C++ draft states: 在[expr.reinterpret.cast] ,C ++草案指出:
A prvalue of type “pointer to member of
X
of typeT1
” can be explicitly converted to a prvalue of a different type “pointer to member ofY
of typeT2
” ifT1
andT2
are both function types or both object types.如果
T1
和T2
都是函数类型或两种对象类型,则可以将类型为“T1
类型X
的成员的指针”的prvalue显式转换为不同类型的prvalue“指向类型为T2
的Y
的成员的指针”。 72 The null member pointer value ( [conv.mem] ) is converted to the null member pointer value of the destination type.72空成员指针值( [conv.mem] )将转换为目标类型的空成员指针值。 The result of this conversion is unspecified, except in the following cases:
除以下情况外,此转换的结果未指定:
converting a prvalue of type “pointer to member function” to a different pointer to member function type and back to its original type yields the original pointer to member value.
将“指向成员函数的指针”类型的prvalue转换为指向成员函数类型的不同指针,并返回其原始类型,从而生成指向成员值的原始指针。
converting a prvalue of type “pointer to data member of
X
of typeT1
” to the type “pointer to data member ofY
of typeT2
” (where the alignment requirements ofT2
are no stricter than those ofT1
) and back to its original type yields the original pointer to member value.类型的prvalue转换“指针的数据成员
X
型的T1
”的类型“指针的数据成员Y
类型的T2
”(其中的对准要求T2
并不比那些更严格的T1
),并返回到其原始type产生指向成员值的原始指针。
72)
T1
andT2
may have different cv -qualifiers, subject to the overall restriction that areinterpret_cast
cannot cast away constness.72)
T1
和T2
可能具有不同的cv-限定符 ,受限于reinterpret_cast
不能丢弃const的总体限制。
Since you are converting your "pointer to member function" to a different "pointer to member function" type and back, it yields the original value. 由于您将“指向成员函数的指针”转换为另一个“指向成员函数的指针”类型并返回,因此它会生成原始值。 This is both legal and well-defined behaviour.
这是合法且定义明确的行为。 So your code should work properly.
所以你的代码应该正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.