如何以与 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的使用。

有没有更好的选择?

您可以将函数指针的"新"名称设置为对"原始"的引用。"对函数指针的引用"的语法很混乱,因此事先使用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;
};

最新更新