【问题标题】:Cast one pointer-to-member-function to another of same class将一个指向成员函数的指针转换为同一类的另一个
【发布时间】:2016-09-05 04:23:55
【问题描述】:

使用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;
}

【问题讨论】:

    标签: c++ member-function-pointers reinterpret-cast


    【解决方案1】:

    [expr.reinterpret.cast],C++ 草案指出:

    如果T1,“指向T1 类型的X 成员的指针”类型的纯右值可以显式转换为不同类型的“指向T2 类型的Y 成员的指针”类型的纯右值和T2 都是函数类型或都是对象类型。72 空成员指针值([conv.mem])被转换为目标类型的空成员指针值。此转换的结果未指定,但以下情况除外:

    • 将“指向成员函数的指针”类型的纯右值转换为指向成员函数类型的不同指针并返回其原始类型会产生指向成员值的原始指针。

    • 将“指向X 类型T1 的数据成员的指针”类型的纯右值转换为“指向Y 类型T2 的数据成员的指针”类型(其中的对齐要求T2 并不比T1 更严格)并且返回其原始类型会产生指向成员值的原始指针。

    72) T1T2 可能有不同的 cv-限定词,受制于 reinterpret_cast 不能抛弃 constness 的总体限制。

    由于您将“指向成员函数的指针”转换为不同的“指向成员函数的指针”类型并返回,它会产生原始值。这既是合法的,也是明确定义的行为。所以你的代码应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 2012-05-19
      • 1970-01-01
      相关资源
      最近更新 更多