c – 没有上下文类型信息的重载函数
发布时间:2020-12-16 10:07:49 所属栏目:百科 来源:网络整理
导读:#includeiostream#includestdio.h#includestring.husing namespace std; void cb(int x){ std::cout "print inside integer callback : " x "n" ; }void cb(float x){ std::cout "print inside float callback :" x "n" ;}void cb(std::string x){ std::co
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; void cb(int x) { std::cout <<"print inside integer callback : " << x << "n" ; } void cb(float x) { std::cout <<"print inside float callback :" << x << "n" ; } void cb(std::string& x) { std::cout <<"print inside string callback : " << x << "n" ; } int main() { void(*CallbackInt)(void*); void(*CallbackFloat)(void*); void(*CallbackString)(void*); CallbackInt=(void *)cb; CallbackInt(5); CallbackFloat=(void *)cb; CallbackFloat(6.3); CallbackString=(void *)cb; CallbackString("John"); return 0; } 上面是我的代码,它有三个函数,我想创建三个回调,它们将根据参数调用重载函数. CallbackInt用于调用cb函数,int作为参数,同样休息两个. 但是当用它编译时给出了如下错误. function_ptr.cpp: In function ‘int main()’: function_ptr.cpp:29:21: error: overloaded function with no contextual type information CallbackInt=(void *)cb; ^~ function_ptr.cpp:30:14: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive] CallbackInt(5); ^ function_ptr.cpp:32:23: error: overloaded function with no contextual type information CallbackFloat=(void *)cb; ^~ function_ptr.cpp:33:18: error: cannot convert ‘double’ to ‘void*’ in argument passing CallbackFloat(6.3); ^ function_ptr.cpp:35:24: error: overloaded function with no contextual type information CallbackString=(void *)cb; ^~ function_ptr.cpp:36:24: error: invalid conversion from ‘const void*’ to ‘void*’ [-fpermissive] CallbackString("John"); 解决方法
1)编译器不知道,选择哪个cb超载.
2)即使它确实知道,它也不会在没有任何显式转换的情况下从void *转换为void(*)(int). 但是,如果您为编译器提供足够的信息,它可以推断出它: void cb(int x) { std::cout <<"print inside integer callback : " << x << "n" ; } void cb(float x) { std::cout <<"print inside float callback :" << x << "n" ; } void cb(const std::string& x) { std::cout <<"print inside string callback : " << x << "n" ; } int main() { void(*CallbackInt)(int); void(*CallbackFloat)(float); void(*CallbackString)(const std::string&); CallbackInt = cb; CallbackInt(5); CallbackFloat = cb; CallbackFloat(6.3); CallbackString = cb; CallbackString("John"); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |