Reputation: 3555
I've tried several variations of this with no joy...
auto& hrctp = std::chrono::high_resolution_clock::time_point;
auto& hrcn = std::chrono::high_resolution_clock::now;
I know I can use...
use namespace std::chrono::high_resolution_clock;
And I understand one shouldn't try too hard to replicate the paradigms of one language in another but I'm just curious. Is there an equivalent?
Upvotes: 4
Views: 1205
Reputation: 17036
It's simple. Short answer... It's different for types and functions.
// Alias the type...
using hr_time_point = std::chrono::high_resolution_clock::time_point;
// Create reference (like an alias) for the function
auto &hr_now = std::chrono::high_resolution_clock::now;
The compiler will undoubtedly optimize away the reference, and call the referent directly.
This would work equally well:
inline auto hr_now() { return std::chrono::high_resolution_clock::now(); }
Again, the optimizer will optimize out the indirection.
Upvotes: 2
Reputation: 29017
This is more complex than it looks. As Cheers and hth says, aliasing is different for types and functions and namespaces.
For a simple type like std::chrono::high_resolution_clock::time_point
, you can either use typedef
or using
:
using hrctp = std::chrono::high_resolution_clock::time_point;
or
typedef std::chrono::high_resolution_clock::time_point hrctp;
The advantage of using
is that you can use it for template classes too.
For a static member function or a stand-alone function embedded in a namespace, you can just use a pointer to the function:
const auto hrcn = std::chrono::high_resolution_clock::now;
You can't do this for non-static member functions (a pointer-to-member-function is a completely different beast), but fortunately you don't need to (because you invoke non-static member functions on an object of the appropriate type).
The options for time_point
are purely done at compile time. However the function alias may impose a run-time penalty (because you are calling the function through a pointer, rather than jumping there directly). However, write your code for clarity first, and speed second. (OTOH, the C++ way would probably be:
using hrc =std::chrono::high_resolution_clock;
and then use hrc::time_point
and hrc::now
.
Upvotes: 2
Reputation: 11787
If you want to define an alias, use a using
directive. That means this would work:
using hrctp = std::chrono::high_resolution_clock::time_point;
For the function, you could use something like this:
const auto hrcn = std::chrono::high_resolution_clock::now;
This creates a function pointer to the static function.
Upvotes: 2