我有一个有几个算法的模型,我必须用不同的方式对这些算法进行多次测试。为了测试(在这么多文件中),我很难更改类中的任何内容,这是非常困难的。我想告诉编译器在哪个对象上运行哪个方法。每次,我有两个算法要比较,我有超过10个测试文件test1.cpp . test10.cpp .。因此,很难调整每个测试文件。算法的名称在每个文件中也不同。我正在寻找一种将方法从profiler传递给main的方法。事实上,每件事都是从主开始调整的。我只将算法复制/通过到模型类中,然后修复主函数,而不更改类内的任何内容(在复制/粘贴算法之后)或配置文件函数。下面的代码显示了我需要的内容。可以随意调整此代码的结构,而不必将模型类分解为两个类。我只能上一节课。
请不要发送(迁移)这个问题到代码审查,因为这是一个草案代码(上次我得到这么多的选票,只是因为错误的人)。
欢迎来到最简单、最易读的建议。
#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;
}发布于 2015-04-17 00:51:11
有关更多详细信息,请参阅C++, function pointer to member function。
发布于 2015-04-17 01:03:14
用这种方式改变分析器功能怎么样?
#include <functional>
void profiler(std::function<void()> func) {
// CTimer mytimer;
// mytimer.start();
func();
// mytimer.stop();
// std::cout<<"time elapsed: "<<mytimer.duration;
}使用分析器:
CModel m1, m2;
profiler([&m1](){
double d = m1.algorithm1();
});
profiler([&m2](){
double d = m2.algorithm2();
});如果可能的话,也可以是同一个对象:
CModel m1;
profiler([&m1](){
double d = m1.algorithm1();
});
profiler([&m1](){
double d = m1.algorithm2();
});https://stackoverflow.com/questions/29688360
复制相似问题