为什么一次包装 typedef 函数签名与原始签名不匹配

Why once wrap typedef function signature doesn't match the original signature

本文关键字:函数 不匹配 原始 typedef 包装 一次 为什么      更新时间:2023-10-16

为什么这段代码先打印1,然后打印0?

typedef void (* GLFWkeyfun)(GLFWwindow*,int,int,int,int);
std::cout << std::is_same<GLFWkeyfun, void(*)(GLFWwindow*, int, int, int, int)>::value << std::endl;
std::cout << std::is_same<std::function<GLFWkeyfun>, std::function<void(GLFWwindow*, int, int, int, int)>>::value << std::endl;

请注意,GLFWkeyfun是函数指针类型。相反,函数类型被指定为std::function<void(GLFWwindow*, int, int, int, int)>std::function的模板参数。

我们应该将函数类型指定为std::function。您可以在GLFWkeyfun上应用std::remove_pointer,例如

std::cout << std::is_same<std::function<std::remove_pointer_t<GLFWkeyfun>>,
//                                      ^^^^^^^^^^^^^^^^^^^^^^          ^ 
std::function<void(GLFWwindow*, int, int, int, int)>>::value
<< std::endl;

如果你的编译器不支持C++14,那么

std::cout << std::is_same<std::function<std::remove_pointer<GLFWkeyfun>::type>,
//                                      ^^^^^^^^^^^^^^^^^^^^          ^^^^^^^
std::function<void(GLFWwindow*, int, int, int, int)>>::value
<< std::endl;

演示