0

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>();
user3731622
  • 4,844
  • 8
  • 45
  • 84

1 Answers1

2

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.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • Awesome! You can probably tell I'm relatively new to templates. I did not know I needed to specify `typename` before `D::rep` on the return value. If you have a reference where I can read more about this, I would appreciate the direction. – user3731622 Oct 19 '15 at 19:26
  • 1
    take a deep breath: http://en.cppreference.com/w/cpp/language/dependent_name – Richard Hodges Oct 19 '15 at 19:29