编辑: 这个问题最初的标题是“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/