Search code examples
c++timerc++-chronofunction-template

Template function with chrono::duration parameter and returning result of chrono::duration::count


I'm trying to write a function that allows the user to specify a chrono::duration like chrono::seconds and return the result of chrono::duration::count.

I'm able to do this using the following template function:

template<typename D, typename Rep>
Rep getTimeSinceStart(){
    return chrono::duration_cast<D>(chrono::steady_clock::now() - start).count();
    };

To call this function, I must specify the type for Rep. For example, assuming I have an object called timer, if Rep is a long long:

long long sinceStart = timer.getTimeSinceStart<chrono::seconds, long long>();

However, is there a way to just specify the chrono::duration?

I was thinking something like:

template<typename D>
D.rep getTimeSinceStart(){
    return chrono::duration_cast<D>(chrono::steady_clock::now() - start).count();
};

This way I could just call:

long long sinceStart = timer.getTimeSinceStart<chrono::seconds>();

Solution

  • something like this:

    #include <thread>
    #include <iostream>
    #include <chrono>
    
    const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
    
    template<typename D>
    typename D::rep getTimeSinceStart(){
        return std::chrono::duration_cast<D>(std::chrono::steady_clock::now() - start).count();
    };
    
    int main (int argc, char **argv)
    {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        long long sinceStart = getTimeSinceStart<std::chrono::seconds>();
        std::cout << "since start: " << sinceStart << std::endl;
    
    }
    

    in the above code, start is a global - you will want to make it a member of your class.