我有一个版本的代码带有启用或禁用宏的基准测试,我想更改我可以打开和关闭基准设置的代码,而无需重新编译我的代码并且没有很多 if-else 或没有代码重复(有基准的版本和没有基准的版本)?
为正确的函数设置 vtable 的方法?
编辑:为我不习惯做的事情添加了代码示例
EDIT V2 我从答案中了解到没有办法,所以如果我创建两个共享对象,我可以在运行时编码链接到哪个吗?
#include <iostream>
#include <string>
using namespace std;
struct A
{
virtual int add(int a,int b)=0;
};
struct B:public A
{
virtual int add(int a,int b){return a+b;}
};
struct C:public A
{
virtual int add(int a,int b)
{
cout << "time" << endl;
return a+b;
}
};
int main(int argc,char* argv[])
{
A* a;
string s(argv[1]);
if(s.compare("t"))
{
a = new C;
}
else
{
a=new B;
}
cout << a->add(2,5);
return 0;
}
最佳答案
A way to set the vtable for the correct functions?
Vtable 是一个实现细节。这个细节的正常实现方式是 vtable 指针由构造函数设置。
您可以拥有一个接口(interface)和一个设置一次并多次使用的工厂函数指针(也称为 Factory design pattern )。例如:
#include <memory>
struct A {
virtual void f() = 0;
virtual ~A() noexcept = default;
};
std::unique_ptr<A>(*factory)(); // Factory function.
struct A1 : A {
void f() override;
};
struct A2 : A {
void f() override;
};
int main(int ac, char** av) {
if(ac >= 1 && **av == 'd')
factory = []() { return std::unique_ptr<A>(new A2); };
else
factory = []() { return std::unique_ptr<A>(new A1); };
auto a = factory();
}
关于c++ - 有没有办法根据用户参数设置函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57956615/