创建函数别名

时间:2015-03-06 23:25:54

标签: c++ c++11 inline stdbind

编辑:这个问题原本标题为“使用std::bind创建内联函数”,但这并不是我真正想要的:我只是想要一种简单的方法来对函数进行别名。

我想将std::chrono::high_resolution_clock::now公开为独立函数。也就是说,我想做以下事情:

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

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

5 个答案:

答案 0 :(得分:3)

我不认为无论如何都要这样做,因为bind不是constexpr。

同样,lambdas也不具备可靠性。

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

答案 1 :(得分:3)

如果我想创建一个简单的函数别名

,这就是我的工作
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&&实际上是函数的直接别名,而所有其他方法都有一定程度的间接。 (虽然在编译之后,可以被内联函数调用替换。也许。)

答案 2 :(得分:2)

添加另一个答案'因为它需要与你想要的东西截然不同。

在这种情况下不需要std :: bind,因为没有发生“绑定”。

但是我觉得这可能导致一些令人困惑的问题,因为current_time实际上不是别名,就像使用decarations一样。

#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;
}

答案 3 :(得分:2)

保持简单。

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

答案 4 :(得分:1)

使用GCC可以创建“功能别名”,但仅适用于在同一翻译单元中定义且您知道错位名称的功能,因此无法对std::chrono::high_resolution_clock::now()进行可靠操作

请参阅https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

上的alias属性
相关问题