简体   繁体   中英

Passing lambda to template function

I have the following code:

template <typename L>
double measure( L&& action )
{
    using namespace std::chrono;

    high_resolution_clock::time_point start, end;
    duration<double> timeSpan;

    start = high_resolution_clock::now();
    action();
    end = high_resolution_clock::now();

    timeSpan = duration_cast<milliseconds>(end - start);
    return timeSpan.count();
}

and I use it like this:

    cout << measure([](){ mergeSort<float>(array, 0, 10000); }) << endl << endl;

And so far, this is the only way I know to pass lambda functions. BUT, I was trying to make this function more complete, allowing to pass a ratio<> as template argument, to specify the ratio<> of the timeSpan template, to return time in other measure than milliseconds...

So, I want to know how can I pass multiple template arguments to a function and pass a lambda together. What should I specify on the template as the lambda's type or, what else can I do to achieve something like this:

    timer::measure<ratio<1,1000>>([](){ mergeSort<float>(array, 0, 10000); })

?

You can just have something like this:

template <typename Ratio, typename L>
//        ^^^^^^^^^^^^^^^^
double measure( L&& action )
{
    using namespace std::chrono;

    auto start = high_resolution_clock::now();
    action();
    auto end = high_resolution_clock::now();

    auto timeSpan = duration_cast<duration<double, Ratio>>(end - start);
    //                            ^^^^^^^^^^^^^^^^^^^^^^^
    return timeSpan.count();
}

Live demo

First of all, the standard way to pass lambda functions is to use std:function :

#include <functional>

...

double measure( std::function<void()> action ){
    ...
}

Then use it in the same way you use

cout << measure([&](){ mergeSort<float>(array, 0, 10000); }) << endl << endl;

Then, you can apply Jefffrey's answer with removal of template parameter L .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM