convert seconds as double to std::chrono::duration?

Don't do std::chrono::seconds(timeToSleep). You want something more like:

std::chrono::duration<double>(timeToSleep)

Alternatively, if timeToSleep is not measured in seconds, you can pass a ratio as a template parameter to duration. See here (and the examples there) for more information.


Making the answer from @Cornstalks a little more generic, you could define a function like this:

template <typename T>
auto seconds_to_duration(T seconds) {
    return std::chrono::duration<T, std::ratio<1>>(seconds);
}

This will convert a seconds value of any primitive type to a chrono duration. Use it like this:

const double timeToSleep = GetTimeToSleep();
std::this_thread_sleep_for(seconds_to_duration(timeToSleep));

const unsigned long timeToSleep = static_cast<unsigned long>( GetTimeToSleep() * 1000 );
std::this_thread::sleep_for(std::chrono::milliseconds(timeToSleep));

Tags:

C++

C++11

Chrono