【发布时间】:2015-04-23 17:21:04
【问题描述】:
谁能帮我实现这段代码?
我需要将一个函数传递给另一个函数:
std::cout << process_time(Model::method1) << std::endl;
该函数将函数作为模板类型获取并在对象上调用它
template <typename F>
double process_time(F algorithm)
{
Model model;
double time=0;
do
{
// ...
time += model.algorithm(arg1);
} while (! stop_criteria);
return time;
}
注意method1 也是一个函数模板:
template <typename T>
double method1(std::vector<T> &v)
{
...
}
它的合法语法是什么?
main.cpp
#include <iostream>
#include <vector>
class Model
{
public:
template <typename T>
double method1(std::vector<T> &v)
{
double t = 0;
//...
return t;
}
template <typename T>
double method2(std::vector<T> &v)
{
double t = 0;
//...
return t;
}
};
template <typename F>
double process_time(F algorithm)
{
Model model;
double time = 0;
bool stop_criteria = false;
do
{
std::vector<int> arg1;
// ...
time += model.algorithm(arg1);
} while (!stop_criteria);
return time;
}
int main()
{
std::cout << process_time(Model::method1) << std::endl;
return 0;
}
【问题讨论】:
-
什么是
method1?你想做什么?你能提供一个MCVE -
什么是
process_time? -
@anxieux 抱歉,已修复
标签: c++ templates c++11 argument-passing