创建函数别名
Creating a function alias
编辑:这个问题的最初标题是"使用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;
- 使用定义函数模板别名
- 如何同时别名和实例化模板函数?
- 通过类型别名从构造函数转发模板推导
- typedef 别名的析构函数
- 函数的返回值类型是别名 ***或 *** 布尔值
- std::shared_ptr 使用别名构造函数,是否可以检索初始指针值?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 在模板派生类中继承具有类型别名的构造函数
- 模板类函数指针类型别名
- 使用函数数据类型键入别名和别名模板
- 是否可以为模板类的模板函数成员设置别名?
- 类方法和全局函数中的别名
- 别名一个模板函数,该功能没有参数可更简洁
- MSVC:带函数的"error C2244: unable to match function definition to an existing declaration"是指专用模板类的类型别名
- 为 OpenMP 函数创建别名 ||部分禁用 openMP
- Cython 创建 C 函数别名
- C++最佳实践 - 函数类型别名 std::function<T> 或 T
- 使用使用成员类型别名的构造函数来推论类模板参数
- 如何自己为我自己的shared_ptr实现实现别名构造函数
- 具有已知类型的别名函数模板