python的导入C++等价物是什么?

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

本文关键字:是什么 等价物 C++ 导入 python      更新时间:2023-10-16

我已经尝试了几种变体,但没有乐趣......

auto& hrctp = std::chrono::high_resolution_clock::time_point;
auto& hrcn = std::chrono::high_resolution_clock::now;

我知道我可以使用...

use namespace std::chrono::high_resolution_clock;

我知道人们不应该太努力地在另一种语言中复制一种语言的范式,但我只是好奇。有等价物吗?

这比看起来更复杂。 正如 Cheers 和 hth 所说,类型、函数和命名空间的别名是不同的。

对于像std::chrono::high_resolution_clock::time_point这样的简单类型,您可以使用typedefusing

using hrctp = std::chrono::high_resolution_clock::time_point;

typedef std::chrono::high_resolution_clock::time_point hrctp;

using的优点是您也可以将其用于模板类。

对于静态成员函数或嵌入在命名空间中的独立函数,只需使用指向该函数的指针:

const auto hrcn = std::chrono::high_resolution_clock::now;

你不能对非静态成员函数这样做(指向成员函数的指针是一个完全不同的野兽),但幸运的是你不需要这样做(因为你在适当类型的对象上调用非静态成员函数)。


time_point的选项纯粹是在编译时完成的。 但是,函数别名可能会造成运行时损失(因为您是通过指针调用函数,而不是直接跳到那里)。 但是,首先编写代码以使其清晰,其次才是速度。 (OTOH,C++方式可能是:

using hrc =std::chrono::high_resolution_clock;

然后使用hrc::time_pointhrc::now.

如果要定义别名,请使用using指令。这意味着这将起作用:

using hrctp = std::chrono::high_resolution_clock::time_point;

对于该函数,您可以使用如下内容:

const auto hrcn = std::chrono::high_resolution_clock::now;

这将创建一个指向静态函数的函数指针。

很简单。 简短的回答...类型和功能不同。

// 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;

编译器无疑会优化引用,并直接调用引用对象。

这同样有效:

inline auto hr_now() { return std::chrono::high_resolution_clock::now(); }

同样,优化器将优化间接寻址。