【发布时间】:2013-01-13 00:26:18
【问题描述】:
我在下面写的函数是计算处理一个函数需要多长时间。
// 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;
}
standardDivation 是用模板制作的,因此它可以接受任何 c++ 容器,我想对 timeFunction 做同样的事情,所以我尝试了以下方法。
template<typename T>
clock_t timeFuction(double(*f)(T), T v)
{
auto start = clock();
f(v);
return clock() - start;
}
但这给了我错误,例如不能使用函数模板“双重标准Divation(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++ 容器。任何帮助是极大的赞赏。
【问题讨论】:
-
您正在尝试传递一个指向函数模板的指针。但不存在这样的事情。
-
你用的是什么编译器?似乎在 g++ 4.6.3 上对我来说工作正常
-
对我来说也很好 g++ 4.6.3
-
按值传递大对象不是一个好主意,因为它需要大量复制,而是通过 const 引用传递。
标签: c++ function templates parameters containers