Search code examples
c++c++11timec++14user-defined-literals

C++: setting time using suffixes


Tell me, Can the following exist in C ++ 11/14/17:

1) set time using time suffixes

double time1 = 1s; // time1 = 1.0
double time2 = 2m; // time2 = 120.0
double time3 = 7ms; // time3 = 0.007 

2) get the string value of the time with the suffix as set

std::cout << getTime(time1); // cout 1s
std::cout << getTime(time2); // cout 2s
std::cout << getTime(time3); // cout 7ms

Solution

    1. Yes, as of C++14, you can use the user-defined literals described here to create durations:

      #include <chrono>
      using namespace std::literals;
      auto time1 = 1s; // std::chrono::seconds{1}
      auto time2 = 2min; // std::chrono::minutes{2}
      auto time3 = 7ms; // std::chrono::milliseconds{7}
      

      These create type-safe objects that store an integral value. You can use double internally fairly easily, but those specializations don't come with a pretty type alias out of the box:

      namespace chr = std::chrono;
      using dbl_seconds = chr::duration<double, chr::seconds::period>;
      // Likewise for other units
      dbl_seconds time1 = 1s;
      

      If you absolutely need the internal value (usually a bad idea), you can access it with .count().

    2. This is planned to come in C++20:

      std::cout << time1; // 1s, or 1.000000s if using double
      

      Until then, the best you can do with standard C++ is to suck it up and use count():

      std::cout << time1.count() << 's'; // 1s
      

    For a good look into the library, watch Howard's CppCon talk. His other talks cover the planned C++20 additions.