【问题标题】:Pass a function as a parameter with templates in C++?在 C++ 中使用模板将函数作为参数传递?
【发布时间】: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


【解决方案1】:

我尝试在 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;
}

【讨论】:

  • 我正在使用 Microsoft Visual Studio 2012。我目前正在下载 Visual Studio 2010,我将尝试使用它来编译代码。
  • 它在 MinGW-g++-4.6.2 上也能很好地编译
  • 我指定了模板参数并且它有效。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2018-07-30
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-02
相关资源
最近更新 更多