2013-07-27 34 views
15

Tôi đang sử dụng C++ 11 <chrono> và có một số giây được biểu thị dưới dạng gấp đôi. Tôi muốn sử dụng C++ 11 để ngủ trong thời gian này, nhưng tôi không thể hiểu cách chuyển đổi nó thành đối tượng std::chrono::duration mà yêu cầu std::this_thread::sleep_for.chuyển đổi giây thành kép thành std :: chrono :: duration?

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

Tôi đã bị khóa tại tham chiếu <chrono> nhưng tôi thấy nó khá khó hiểu.

Cảm ơn

EDIT:

Sau đây cho lỗi:

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

lỗi:

:\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

Câu trả lời của cây ngô là chính xác. Điều này trông giống như một lỗi trong VS11 'std :: this_thread :: sleep_for'. Bạn có thể thử 'std :: this_thread :: sleep_for (std :: chrono: duration_cast (duration))' để làm việc xung quanh lỗi. Tôi đã chọn mili giây tùy ý. Sử dụng bất kỳ công trình nào, nhưng hãy để '' cung cấp các chuyển đổi thay vì tự chuyển đổi. –

Trả lời

16

Đừng làm std::chrono::seconds(timeToSleep). Bạn muốn một cái gì đó giống như hơn:

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

Ngoài ra, nếu timeToSleep không đo bằng giây, bạn có thể vượt qua một tỷ lệ như một tham số mẫu để duration. Xem here (và các ví dụ ở đó) để biết thêm thông tin.

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); 
Các vấn đề liên quan