我在下面写的函数是用来计时处理一个函数需要多长时间的。
// return type for func(pointer to func)(parameters for func), container eg.vector
clock_t timeFuction(double(*f)(vector<double>), vector<double> v)
{
auto start = clock();
f(v);
return clock() - start;
}
这是我想在我的 timeFunction 中测试的函数。
template<typename T>
double standardDeviation(T v)
{
auto tempMean = mean(v); //declared else where
double sq_sum = inner_product(v.begin(), v.end(), v.begin(), 0.0);
double stdev = sqrt(sq_sum / v.size() - tempMean * tempMean);
return stdev;
}
standardDiviation 是用模板制作的,因此它可以接受任何 c++ 容器,我想对 timeFunction 做同样的事情,所以我尝试了以下方法。
template<typename T>
clock_t timeFuction(double(*f)(T), T v)
{
auto start = clock();
f(v);
return clock() - start;
}
但这给了我错误,比如不能使用函数模板“double standardDiviation(T)”和不能为“重载函数”推断模板参数
这就是我在 main 中调用函数的方式。
int main()
{
static vector<double> v;
for( double i=0; i<100000; ++i )
v.push_back( i );
cout << standardDeviation(v) << endl; // this works fine
cout << timeFuction(standardDeviation,v) << endl; //this does not work
}
我如何修复 timeFunction 以便它适用于任何 C++ 容器。任何帮助是极大的赞赏。
最佳答案
我试图在 GCC 4.7.1 上编译这段代码。它编译并工作正常。你使用什么编译器?如果无法推导出模板参数,则尝试明确指定它,即使用:
cout << timeFuction(standardDeviation< vector<double> >,v) << endl;
此外,在提问时,您应该尝试删除所有不必要的代码。
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
double standardDeviation(T v)
{
return 5;
}
template<typename T>
int timeFuction(double(*f)(T), T v)
{
// auto start = clock();
f(v);
return 0;//clock() - start;
}
int main()
{
static vector<double> v;
for( double i=0; i<100000; ++i )
v.push_back( i );
cout << standardDeviation(v) << endl; // this works fine
cout << timeFuction(standardDeviation,v) << endl; // this also work
return 0;
}
关于c++ - 在 C++ 中将函数作为参数传递给模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14299406/