创建函数别名

Kyl*_*and 5 c++ inline stdbind c++11

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

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

auto current_time = std::bind(std::chrono::high_resolution_clock::now);
Run Code Online (Sandbox Code Playgroud)

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

Cof*_*ode 7

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

constexpr auto &&now = std::chrono::high_resolution_clock::now;
Run Code Online (Sandbox Code Playgroud)

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

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)...);
}
Run Code Online (Sandbox Code Playgroud)

我之所以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';
}
Run Code Online (Sandbox Code Playgroud)

我得到以下结果:

0x4007c0
0x400a50
0x400ae8
0x4007c0
Run Code Online (Sandbox Code Playgroud)

表明只有auto&&实际上是函数的直接别名,而所有其他方法都有一定程度的间接性。(虽然,编译后它们可能会被内联函数调用替换。也许。)