重载函数,没有上下文类型信息

时间:2017-09-02 18:22:02

标签: c++ c++11 function-pointers

#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");

2 个答案:

答案 0 :(得分:7)

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;

}

答案 1 :(得分:0)

对于第一个错误,请使用static cast指定所需的重载,例如here

对于其余的,你不能有意义地将int或float转换为void *。不知道你想在这里做什么。

CallbackInt应该采用int参数...