提问者:小点点

如何以API兼容的方式重命名类成员?


给定一个相当简单的结构:

struct IMyClass {
    void (*f1)();
    void (*f2)();
    void (*f3)();
};

是否可以以API兼容的方式“重命名”IMYClass::f2? 我的意思是给成员另一个名字,例如:

struct IMyClass {
    void (*f1)();
    union {
        void (*f2)();
        void (*f2_new)();
    };
    void (*f3)();
};

这是否是一种有效且符合标准的方法? 我最关心的是联合的非静态成员的生存期是否会妨碍f2f2_new的使用。

有没有更好的替代方案?


共2个答案

匿名用户

您可以将函数指针的“新”名称作为对“原始”的引用。 “引用指向函数的指针”的语法比较混乱,因此预先使用typedefusing...行会清楚得多:

using pvf = void (*)();

struct IMyclass {
    pvf f1;
    pvf f2;
    pvf f3;
    pvf& f2_new = f2; // f2_new() will just 'redirect' to f2()
//  void (*&f2_new)() = f2; // The 'messy' way without using using.
};

void test1()
{
    std::cout << "test1" << std::endl;
}
void test2()
{
    std::cout << "test2" << std::endl;
}

int main()
{
    IMyclass imc;
    imc.f2 = test1;
    imc.f2_new();
    imc.f2 = test2;
    imc.f2_new();
    // Function (re-)assignment via the reference works, too...
    imc.f2_new = test1;
    imc.f2();
    return 0;
}

匿名用户

有没有更好的替代方案?

是的。 看起来你在重新发明虚拟函数。 有什么理由不用那个代替吗?

即,而不是:

struct IMyClass {
    void (*f1)();
    void (*f2)();
    void (*f3)();
};

为什么不使用:

struct IMyClass {
    virtual void f1() = 0;
    virtual void f2() = 0;
    virtual void f3() = 0;
};

并有具体的实现。

我需要的是保持像myClass->f2()这样的旧代码正常工作,同时引入一些方法,将函数用作myClass->f2_new(),并且保持ABI(内存布局等)相同。

请尝试执行以下操作:

struct specialized: public IMyClass 
{
    virtual void f2_new() = 0;
};