创建函数别名

Creating a function alias

本文关键字:别名 函数 创建      更新时间:2023-10-16

编辑:这个问题的最初标题是"使用std::bind创建内联函数",但这并不是我真正想要的:我只是想要一种简单的方法来别名函数。

我想将std::chrono::high_resolution_clock::now公开为独立函数。也就是说,我想执行以下操作:

auto current_time = std::bind(std::chrono::high_resolution_clock::now);

不幸的是,由于这是在头文件中,因此在链接时会导致current_time的多个定义。有没有办法从std::bind返回内联函数

如果我想创建一个简单的函数别名,我会这样做

constexpr auto &&now = std::chrono::high_resolution_clock::now;

如果我想创建一个将内联的完整包装器别名

template<typename ... Args>
inline constexpr auto now(Args &&... args) -> decltype(std::chrono::high_resolution_clock::now(std::forward<Args>(args)...)){
    return std::chrono::high_resolution_clock::now(std::forward<Args>(args)...);
}

我之所以在别名定义中使用通用引用auto&&,是因为有可能addressof(now) == addressof(std::chrono::high_resolution_clock::now).

在我的运行 G++ 4.9.2 的系统上:

constexpr auto &&now_ref = std::chrono::high_resolution_clock::now;
constexpr auto now_var = std::chrono::high_resolution_clock::now;
template<typename ... Args>
inline constexpr auto now_wrapper(Args &&... args)
    -> decltype(std::chrono::high_resolution_clock::now(std::forward<Args>(args)...)){
    return std::chrono::high_resolution_clock::now(std::forward<Args>(args)...);
}
int main(int argc, char *argv[]){
    std::cout << std::hex << std::showbase;
    std::cout << (uintptr_t)std::addressof(std::chrono::high_resolution_clock::now) << 'n';
    std::cout << (uintptr_t)std::addressof(now_wrapper<>) << 'n';
    std::cout << (uintptr_t)std::addressof(now_var) << 'n';
    std::cout << (uintptr_t)std::addressof(now_ref) << 'n';
}

我得到以下结果:

0x4007c0
0x400a50
0x400ae8
0x4007c0

表明只有auto&&实际上是函数的直接别名,而所有其他方法都具有某种程度的间接性。(尽管在编译后,它们可能会被内联函数调用所取代。也许吧

我认为无论如何都没有这样做,因为绑定不是constexpr。

此外,lambda 也不可连续。

编辑:有这个技巧可以使类似 constexpr 的 lambda http://pfultz2.com/blog/2014/09/02/static-lambda/

添加另一个答案,因为它需要与你想要的非常不同的策略。

在这种情况下,std::bind 不是必需的,因为没有发生"绑定"。

但是,我觉得这可能会导致一些令人困惑的问题,因为current_time并不是与使用delcaration相同的别名。

#include <iostream>
#include <chrono>
using namespace std;
auto constexpr current_time = std::chrono::high_resolution_clock::now;
int main() {
    auto now = current_time();
    cout << std::chrono::system_clock::to_time_t(now) << endl;
    return 0;
}

使用 GCC 可以创建"函数别名",但仅适用于在同一翻译单元中定义的函数,并且您知道其损坏的名称,因此无法可靠地执行std::chrono::high_resolution_clock::now()

请参阅 https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 中的alias属性

保持简单。

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