为什么一旦换行typedef函数签名与原始签名不匹配

时间:2019-11-06 06:25:35

标签: c++ function type-conversion

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

1 个答案:

答案 0 :(得分:4)

请注意,GLFWkeyfun是函数 pointer 的类型。而是将函数类型指定为std::functionstd::function<void(GLFWwindow*, int, int, int, int)>的模板参数。

我们应该将函数类型指定为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;

Demo