简体   繁体   English

具有可变参数的函数作为函数 C++ 的参数

[英]Function with variable parameters as parameter to function C++

I am trying to create measuring class with one function that take function to be measured as parameter.我正在尝试使用一个函数创建测量类,该函数将要测量的函数作为参数。 Its called ChronoTimer.h content is:其名为 ChronoTimer.h 的内容是:

#include <chrono>

template<typename TimeT = std::chrono::milliseconds, class ClockT = 
std::chrono::system_clock>

class ChronoTimer {
public:
    template<typename F, typename ...Args>

    static typename TimeT::rep duration(F func, Args&&... args)
    {
        auto start = ClockT::now();
        func(std::forward<Args>(args)...);
        return  std::chrono::duration_cast<TimeT>(ClockT::now() - start);
    }
};

Then I have "someClass" where is a function i want measure, and a function where I want to measure the function然后我有“someClass”,我想测量一个函数,以及一个我想测量函数的函数

#include "ChronoTimer.h"
long int someClass::measuredF( long end ) {
    long int cnt = 0;
    for ( long int i = 0; i < end; ++i ) {
        cnt = cnt + i;
    }
    return cnt;
}

void someClass::someFunction() {
    long int end = 10;
    auto duration = ChronoTimer<>::duration(someClass::*measuredF, end).count();
}

There is an error and i dont have enough understing/knowledge in C++ to get it working.有一个错误,我对 C++ 没有足够的了解/知识来让它工作。 Appreciate any help, thanks感谢任何帮助,谢谢

You should pass a callable object, &someClass::measuredF is not callable, its requires a someClass object.您应该传递一个可调用对象, &someClass::measuredF不可调用,它需要一个someClass对象。

You may do:你可以这样做:

void someClass::someFunction() {
    long int end = 10;
    auto duration = ChronoTimer<>::duration([this](long int end) { this->measuredF(end); }, end).count();
}

or capture all:或捕获所有:

void someClass::someFunction() {
    long int end = 10;
    auto duration = ChronoTimer<>::duration([=]() { this->measuredF(end); }).count();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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