首页 > 解决方案 > 为什么一旦包装 typedef 函数签名与原始签名不匹配

问题描述

为什么这段代码打印 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;

标签: c++functiontype-conversion

解决方案


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

我们应该将函数类型指定为std::function. 您可以申请std::remove_pointerGLFWkeyfun例如

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;

演示


推荐阅读