简体   繁体   中英

What is the C++ equivalent of python's import as?

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?

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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM