Get maximum value for time_t with Visual Studio

I need to get an independent working code platform:

timeval tv; tv.tv_sec = std::numeric_limits<time_t>::max(); 

This code works fine under all Linux OS and Mac OS X.

Unfortunately, in windows this returns -1, for tv.tv_sec.

Then I thought of overriding time_t as follows:

  typedef int time_t; 

This did not work, as the compiler now complains:

 error C2371: 'time_t' : redefinition; different basic types 

How can I get code that runs this code in independent form?

+4
source share
2 answers
 tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max(); 

Alternative without decltype

 template<typename T> void set_max(T& val){val = std::numeric_limits<T>::max();} set_max(tv.tv_sec); 
+12
source

You cannot do this portable. time_t is not even an integral type. It can be a structure or something really.

Since it looks like you are setting the tv_sec member struct timeval, why don't you just use the correct type? This is defined as long int, so you should do:

 tv.tv_sec = std::numeric_limits<long int>::max(); 

Although, now I notice that POSIX says tv_sec is time_t, although MSDN and GNU libc use a long int. These old time APIs, which cannot even distinguish between durations and time points, should definitely be replaced. If you can use C ++ 11 check out std :: chrono.

In any case, std::numeric_limits<std::time_t>::max() really gives the maximum value of time_t even on Windows. The only problem is that the Window definition for timeval :: tv_sec is not time_t as a POSIX mandate, and so casting to long int gets a negative number.

However, this can be fixed on Windows by specifying _USE_32BIT_TIME_T. This will cause the time_t definition to match the type used in timeval for tv_sec, and then your std::numeric_limits<time_t>::max() will work.

+1
source

Source: https://habr.com/ru/post/1381550/


All Articles