c++ - 传递接口(interface)函数的函数指针

标签 c++ pointers function-pointers

我有以下情况,有两个接口(interface):

interface ILLShapeAttribute
{
  virtual void DefineAttribute(const char* pszAttributeName, VARIANT* pvAttributeData) = 0;
};

interface ILLShapeNotification
{
  virtual bool IsUsed(const RECT& rcBounds) = 0;
    virtual void DefineAttribute(const char* pszAttributeName, VARIANT* pvAttributeData) = 0;
}

还有 2 个函数:

INT LlShapeGetAttributeList(LPCWSTR pwszShapefileName, ILLShapeAttribute* pIAttrInfo);
INT LlShapeEnumShapes(LPCWSTR pwszShapefileName, ILLShapeNotification* pIInfo);

在这两个函数中,我想调用同一个函数 IterateRecords2,它应该获取指向函数 DefineAttribute 的指针,例如ILLShapeAttribute::DefineAttributeILLShapeNotification::DefineAttribute

我是这样定义的:

void IterateRecords2(ifstream& file, void (*pDefineAttribute)(const char*, VARIANT*))
{
  pDefineAttribute(NULL, NULL); //will be called with real values
}

到目前为止,代码编译成功,一切正常。但是后来我尝试像

这样调用 IterateRecords2
IterateRecords2(file, pIAttrInfo->DefineAttribute);

IterateRecords2(file, pIInfo->DefineAttribute);

我得到编译器错误:

error C3867: 'ILLShapeAttribute::DefineAttribute': function call missing argument list; use '&ILLShapeAttribute::DefineAttribute' to create a pointer to member

请:我知道,ILLShapeNotification 可以从 ILLShapeAttribute 继承,然后传递 *ILLShapeAttribute 而不是函数指针,但我想了解它是如何工作的。

问题如何将指向DefineAttribute 的指针传递给IterateRecords2

最佳答案

Question: how can I pass the pointer to DefineAttribute to IterateRecords2?

你不能。

指向成员函数的指针与指向函数的指针不兼容,即使兼容,您也需要一个对象来调用它,您不能只调用没有对象的成员函数。

一些选项是:

1) 获取指向成员函数的指针并传递一个对象。

这将解决您的编译器错误,但要能够传递与继承无关的不同类型的对象,您需要将 IterateRecords2 作为模板:

template<typename T>
void IterateRecords2(ifstream& file, T* obj, void (T::*pDefineAttribute)(const char*, VARIANT*))
{
  obj->pDefineAttribute(NULL, NULL);
}

现在你可以像这样使用它:

IterateRecords2(file, pIAttrInfo, &ILLShapeAttribute::DefineAttribute);

或:

IterateRecords2(file, pIInfo, &ILLShapeNotification::DefineAttribute);

2) 将一个对象及其成员函数绑定(bind)到一个可调用类型中,并传递:

void IterateRecords2(ifstream& file, std::function<void(const char*, VARIANT*)> DefineAttribute)
{
  DefineAttribute(NULL, NULL);
}

然后这样调用它:

IterateRecords2(file, std::bind(&ILLShapeAttribute::DefineAttribute, pIAttrInfo));

如果你不能使用 std::functionstd::bind 你可以用 boost::functionboost::bind

关于c++ - 传递接口(interface)函数的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17210176/

相关文章:

C++电话号码程序

c++ - 解析C++的句法结构是否比其他语言更难?

c - 从不兼容指针类型/解引用指针到不完整类型的赋值

c++ - 在 C++ 中使用函数指针成员初始化结构数组

c - 在函数内部时,如何获取它的返回地址?

c++ - 什么是 "::operator new"和 "::operator delete"?

c++ - 同时检查指针或引用类型的 C++ dynamic_cast 的设计考虑

c++ - 通过引用修改数组后,为什么它保持不变?

c - "initialization makes integer from pointer without a cast"数组初始化中逐渐减弱

c++ - C++ 中按钮的简单信号