大佬教程收集整理的这篇文章主要介绍了c – 没有上下文类型信息的重载函数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#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");
但是,如果您为编译器提供足够的信息,它可以推断出它:
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; }
以上是大佬教程为你收集整理的c – 没有上下文类型信息的重载函数全部内容,希望文章能够帮你解决c – 没有上下文类型信息的重载函数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。