c++ - 在 C++ 中将函数作为参数传递给模板?

标签 c++ function templates parameters containers

我在下面写的函数是用来计时处理一个函数需要多长时间的。

// 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/

相关文章:

c# - 从 C++ 到 C# 的数组

c++ - 为什么构造函数只调用一次?

javascript - 在文档更改时调用许多函数

function - 如何在 Julia 中编写一个接受可变数量参数的函数?

c++ - 在显式实例化的情况下,类模板的成员函数是否可以内联?

python - 模板中的django select_related

c++ - 在 Visual Studio 2010 中混合使用异常处理模型会产生什么后果?

c++ - 具有 extern #define 和 typedef 结构的静态库

c - 需要改变不同结构中的公共(public)字段的方法

php - 如何在 symfony 模板中访问 c​​ss 文件中的图像