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

时间:2015-08-19 08:51:28

标签: c++

#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>)}'

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

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; }
相关问题