C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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");

解决方法

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;

}

大佬总结

以上是大佬教程为你收集整理的c – 没有上下文类型信息的重载函数全部内容,希望文章能够帮你解决c – 没有上下文类型信息的重载函数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: