没有匹配的函数调用,使用函数指针

No matching function for call, using a function pointer

本文关键字:函数 指针 函数调用      更新时间:2023-10-16
#include <TestAssert.h>
...
if (TestAssert::Equals(10, "x", 10, "y", 10, f_TestFailedMsg, v_TCResult, 
 s_TestCaseCtrl)) { return; }
f_TestFailedMsg(在基类中)的声明:
void A_AbstractTestStub_Actor::f_TestFailedMsg( const char * 
 apc_FormatString, ... )
{
TestAssert.h (Test_failed_callback_function和Equals的定义)部分:
typedef void (*Test_failed_callback_function)(T_String);
static bool Equals( int lineNumber, T_String valueText, int value, T_String 
 expectedText, int expected, Test_failed_callback_function testFailedMsg, 
 bool & tcResult, P_testCaseCtrl::Base & testCaseCtrl );

Equals的实现(TestAssert.cpp):

bool TestAssert::Equals( int lineNumber, T_String valueText, int value, 
 T_String expectedText, int expected, Test_failed_callback_function 
 testFailedMsg, bool & tcResult, P_testCaseCtrl::Base & testCaseCtrl )
{
    ...

我得到错误:

no matching function for call to 'TestAssert::Equals(int const char [29], 
 int&, const char[4], int, <unresolved overloaded function type>, bool&, 
 P_testCaseCtrl::Base&)
Tester.cpp:181:89: note: candidate is:
 ../TestAssert.h:30:17: note: static bool TestAssert::Equals(int, T_String, 
 int, T_String, int, Test_failed_callback_function, bool&, 
 P_testCaseCtrl::Base&)
../TestAssert.h:30:17: note:   no known conversion for argument 6 
 from '<unresolved overloaded function type>' 
 to 'Test_failed_callback_function {aka void (*)(std::basic_string<char>)}'

如何解决这个错误?

f_TestFailedMsg为非静态成员函数;它需要调用A_AbstractTestStub_Actor类型的对象。不能绑定void (*)(T_String)

有几种方法可以解决这个问题。如果f_TestFailedMsg不需要对象,则将其设置为静态。

如果你想提供成员函数作为参数,并获得一个对象稍后调用它,你可以改变你的Test_failed_callback_function为成员函数指针:

typedef void (A_AbstractTestStub_Actor::*Test_failed_callback_function)(T_String)

显然,这将限制函数是A_AbstractTestStub_Actor的成员,但是你可以做一些模板魔术来接受其他类型的成员。

如果c++ 11可用,最具表现力的选择是将Test_failed_callback_function变为std::function<void(T_String)>,然后用lambda或std::bind绑定对象:

if (TestAssert::Equals(10, "x", 10, "y", 10, 
                       [&my_obj](T_String s){my_obj.f_TestFailedMsg(s);},
                       v_TCResult, s_TestCaseCtrl)) 
{ return; }