【发布时间】:2015-06-23 15:57:24
【问题描述】:
我有一个包含几种算法的模型,我必须以不同的方式多次测试这些算法。我非常困难仅仅为了测试(在这么多文件中)的目的而更改课堂上的任何内容。我想告诉编译器在哪个对象上运行哪个方法。每次,我都有两种算法要比较,我有超过 10 个测试文件 test1.cpp ... test10.cpp ... 。因此很难调整每个测试文件。每个文件中算法的名称也不同。我正在寻找一种将方法从main 传递给profiler 的方法。实际上只从主要调整一切。我只将算法复制/粘贴到模型类中,然后修复主函数而不更改类中的任何内容(在复制/粘贴算法之后)或配置文件函数。以下代码显示了我需要的内容。随意调整此代码的结构,而不会将模型类分成两个类。我必须只留一堂课。
请不要将这个问题发送(迁移)到代码审查,因为它是一个草稿代码(上次我因为某人的错误而获得了如此多的反对票。)
欢迎提出最简单、最易读的建议。
#include <iostream>
class CModel
{
public:
// ....
// ....
// ....
CModel()
{
}
double algorithm1()
{
double result=0;
// ...
return result;
}
double algorithm2()
{
double result=0;
// ...
return result;
}
};
void profiler(CModel &model,double (*algorithm)(void))
{
// CTimer mytimer;
// mytimer.start();
// using model fields here
double result=model.(*algorithm)();
// mytimer.stop();
std::cout<<"out: "<<result<<std::endl;
// std::cout<<"time elapsed: "<<mytimer.duration;
}
int main()
{
CModel m1, m2;
// m1.something= something else;
// m2.something= something else;
profiler(m1,m1.algorithm1); // *** impossible ***
profiler(m2,m2.algorithm2); // *** impossible ***
return 0;
}
【问题讨论】:
标签: c++ algorithm c++11 parameter-passing function-pointers