Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 两个类中的回调函数_C++_Callback - Fatal编程技术网

C++ 两个类中的回调函数

C++ 两个类中的回调函数,c++,callback,C++,Callback,你好,我有一个回调函数的问题。我对C++是比较新的。 我有两类助手和导出器: 助手: 出口商: 我得到了errorC3867函数调用缺少参数列表,我应该使用&Exporter::WriteActor。但我不能解决这个问题。有人能帮我吗?这个问题 假设WriteActor是Exporter的成员函数,则其类型可能为: Bool (Exporter::*)(BaseObject*) 与以下内容不兼容: Bool (*)(BaseObject*) 原因是,在前者中,传递类型为Exporter*的隐

你好,我有一个回调函数的问题。我对C++是比较新的。 我有两类助手和导出器:

助手:

出口商:

我得到了errorC3867函数调用缺少参数列表,我应该使用&Exporter::WriteActor。但我不能解决这个问题。有人能帮我吗?

这个问题 假设WriteActor是Exporter的成员函数,则其类型可能为:

Bool (Exporter::*)(BaseObject*)
与以下内容不兼容:

Bool (*)(BaseObject*)
原因是,在前者中,传递类型为Exporter*的隐式参数,通常在成员函数中可以这样访问,而在后者中则不会发生这种情况

一个解决方案 出于上述原因,在将结果函数传递给RecurseHierarchy之前,需要显式传递Exporter*类型的此隐式参数

在您的情况下,可以使用std::bind,如下所示:

using namespace std::placeholders;
auto fn = std::bind(&Exporter::WriterActor, this, _1);
Int32 count = helper.RecurseHierarchy(doc->GetFirstObject(), fn);
然后修改Helper以获取任何可调用对象:

struct Helper {
    template<typename Fn>
    Int32 RecurseHierarchy(BaseObject* op, Fn callback) {
        Int32 count = 0;
        while (op) {
            if (callback(op)) {
                count++;
                count += RecurseHierarchy(op->GetDown(), callback);
                op = op->GetNext();
            }       
        }
        return count;
    }
};

如果您还想允许传递std::function对象和lambda,则上述更改尤其重要。

尝试使用&Exporter::WriteActor时发生了什么?这似乎需要有关实际导出器声明的更多信息。无法使用它。Visual Studio告诉我类型Bool Exporter::*BaseObject*op与类型IterationCallbackWhat's WriteAction的参数不兼容?首先,您可以减少代码,而且应该减少。这就是说,不能将表达式Obj->函数转换为函数指针,C++根本不支持这个函数。还有std::function,它允许您实现类似的事情,您可以在网上找到示例。同时检查函数和成员函数之间的C++差异,理解这一点是必要的。
using namespace std::placeholders;
auto fn = std::bind(&Exporter::WriterActor, this, _1);
Int32 count = helper.RecurseHierarchy(doc->GetFirstObject(), fn);
struct Helper {
    template<typename Fn>
    Int32 RecurseHierarchy(BaseObject* op, Fn callback) {
        Int32 count = 0;
        while (op) {
            if (callback(op)) {
                count++;
                count += RecurseHierarchy(op->GetDown(), callback);
                op = op->GetNext();
            }       
        }
        return count;
    }
};