简体   繁体   English

将一个指向成员的指针函数转换为同一个类的另一个指针

[英]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 type T1 ” can be explicitly converted to a prvalue of a different type “pointer to member of Y of type T2 ” if T1 and T2 are both function types or both object types. 如果T1T2都是函数类型或两种对象类型,则可以将类型为“ T1类型X的成员的指针”的prvalue显式转换为不同类型的prvalue“指向类型为T2Y的成员的指针”。 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 type T1 ” to the type “pointer to data member of Y of type T2 ” (where the alignment requirements of T2 are no stricter than those of T1 ) and back to its original type yields the original pointer to member value. 类型的prvalue转换“指针的数据成员X型的T1 ”的类型“指针的数据成员Y类型的T2 ”(其中的对准要求T2并不比那些更严格的T1 ),并返回到其原始type产生指向成员值的原始指针。

72) T1 and T2 may have different cv -qualifiers, subject to the overall restriction that a reinterpret_cast cannot cast away constness. 72) T1T2可能具有不同的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM