c++ - 创建函数别名

标签 c++ c++11 inline stdbind

编辑: 这个问题最初的标题是“Using std::bind to create inline function”,但这并不是我真正想要的:我只是想要一个别名函数的简单方法。

我想将 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&& 实际上是函数的直接别名,而所有其他方法都具有一定程度的间接性。 (尽管在编译后它们可能被内联函数调用替换。可能。)

关于c++ - 创建函数别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909358/

相关文章:

c++ - Opencv 编解码器选择对话框未显示

c++ - 如何在创建新对象时使用 = 运算符?

C++ - 为什么可以在复制构造函数中直接访问传递的对象的私有(private)变量?

c++ - 单元测试仅在 ARM 中失败

c++ - 解决多定义的内联函数是一个定义明确的东西吗?

c++ - 特化模板类的内部模板

c++ - 什么时候在带有头文件和目标文件的类方法中使用 'inline' 关键字?

C++ urljoin 等效项

c++ - 对象构造后 shared_from_this 中的 std::bad_weak_ptr 异常

c++ - 根据缓冲区长度将空终止字符数组复制到 std::string