The function i am writing below is made to time how long it takes to process a function.

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

This is the function i want to test in my 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 was made with a template so it can accept any c++ container and i want to do the same with timeFunction, so i tried the following.

template<typename T>
clock_t timeFuction(double(*f)(T), T v)
{
    auto start = clock();
    f(v);
    return clock() - start;
}

but this gives me errors like cannot use function template "double standardDiviation(T)" and could not deduce template argument for "overloaded function"

This is how i called the function in 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

}

how do i fix the timeFunction so it works with any c++ container. Any help is greatly appreciated.

Try cout << timeFunction( standardDeviation<delctype(v)>, v);

Why don't you make your timeFunction a template parameter as well?

You should make the timeFunction function template take a templated parameter as the functor (callable type). Simply put, you could do this:

template <typename F, typename T>
clock_t timeFuction(F f, T v)
{
    auto start = clock();
    f(v);
    return clock() - start;
}

Or, more in the style of C++11, you could use variadic templates to have an even more generic implementation:

template <typename F, typename T...>
clock_t timeFuction(F f, T... args)  // take a functor and a parameter pack (variadic).
{
    auto start = clock();
    f( std::forward<T>(args)... );  // un-pack parameters, forward them to the functor.
    return clock() - start;
}

As for calling the timeFunction function using a function template, you need to do as firstPerson showed (i.e., fully specify the template arguments). A useful trick is to wrap the function call into a callable function object type with a templated call-operator:

struct StandardDeviationCaller {
  template <typename T>
  double operator()(T v) const {
    return standardDeviation(v);
  };
};

// then, you can call timeFunction as follows:
cout << timeFuction(StandardDeviationCaller(), v) << endl;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.