2013-07-27 49 views
15

我正在使用C++ 11 <chrono>並將秒數表示爲double。我想在這段時間內使用C++ 11進行睡眠,但是我無法理解如何將其轉換爲std::this_thread::sleep_for需要的std::chrono::duration對象。將秒轉換爲雙精度到std :: chrono :: duration?

const double timeToSleep = GetTimeToSleep(); 
std::this_thread::sleep_for(std::chrono::seconds(timeToSleep)); // cannot convert from double to seconds 

我鎖定在<chrono>參考,但我覺得它相當混亂。

感謝

編輯:

下面給出了錯誤:

std::chrono::duration<double> duration(timeToSleep); 
std::this_thread::sleep_for(duration); 

錯誤:

:\program files (x86)\microsoft visual studio 11.0\vc\include\chrono(749): error C2679: binary '+=' : no operator found which takes a right-hand operand of type 'const std::chrono::duration<double,std::ratio<0x01,0x01>>' (or there is no acceptable conversion) 
2>   c:\program files (x86)\microsoft visual studio 11.0\vc\include\chrono(166): could be 'std::chrono::duration<__int64,std::nano> &std::chrono::duration<__int64,std::nano>::operator +=(const std::chrono::duration<__int64,std::nano> &)' 
2>   while trying to match the argument list '(std::chrono::nanoseconds, const std::chrono::duration<double,std::ratio<0x01,0x01>>)' 
2>   c:\program files (x86)\microsoft visual studio 11.0\vc\include\thread(164) : see reference to function template instantiation 'xtime std::_To_xtime<double,std::ratio<0x01,0x01>>(const std::chrono::duration<double,std::ratio<0x01,0x01>> &)' being compiled 
2>   c:\users\johan\desktop\svn\jonsengine\jonsengine\src\window\glfw\glfwwindow.cpp(73) : see reference to function template instantiation 'void std::this_thread::sleep_for<double,std::ratio<0x01,0x01>>(const std::chrono::duration<double,std::ratio<0x01,0x01>> &)' being compiled 
+1

Cornstalks的答案是正確的。這看起來像VS11中的一個錯誤'std :: this_thread :: sleep_for'。你可以嘗試'std :: this_thread :: sleep_for(std :: chrono:duration_cast (duration))'來解決這個錯誤。我任意選擇毫秒。使用任何作品,但讓''提供轉換而不是滾動自己的作品。 –

回答

16

不要做std::chrono::seconds(timeToSleep)。你想要更多的東西一樣:

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

另外,如果timeToSleep不以秒爲單位,可以比作爲模板參數傳遞給duration。有關更多信息,請參見here(及其中的示例)。

4
const unsigned long timeToSleep = static_cast<unsigned long>(GetTimeToSleep() * 1000); 
std::this_thread::sleep_for(std::chrono::milliseconds(timeToSleep)); 
0
std::chrono::milliseconds duration(timeToSleep); 
std::this_thread::sleep_for(duration); 
相關問題