c++ - 函数如何返回指向带有函数的函数的指针?

标签 c++ function-pointers

我读过这个问题 How to make a function return a pointer to a function? (C++)

...但我仍然遇到问题。 Index 函数返回一个枚举器函数,该函数采用一个函数,它生成每个索引。函数签名已在 Indexer.hpp 中typedef编辑:

typedef bool (*yield)(Core::Index*);
typedef int (*enumerator)(yield);

...和 ​​Indexer

// Indexer.hpp
class Indexer {

    public:
        enumerator Index(FileMap*);

    private:
        int enumerate_indexes(yield);
};

// Indexer.cpp

enumerator Indexer::Index(FileMap* fMap) {
    m_fmap = fMap;
    // ...

    return enumerate_indexes;
}

int Indexer::enumerate_indexes(yield yield_to) {
    bool _continue = true;

    while(_continue) {
        Index idx = get_next_index();        
        _continue = yield_to(&idx);
    }

    return 0;
}

编译器失败并出现以下错误:

Indexer.cpp: In member function 'int (* Indexer::Index(FileMap*))(yield)':
Indexer.cpp:60:12: error: cannot convert 'Indexer::enumerate_indexes' from  
type 'int (Indexer::)(yield) {aka int (Indexer::)(bool (*)(Core::Index*))}' to  
type 'enumerator {aka int (*)(bool (*)(Core::Index*))}'

我的声明中遗漏了什么?

最佳答案

Indexer.hpp 中,typedef 需要告诉编译器 enumerator 是一个 Indexer 成员方法:

typedef int (Indexer::*enumerator)(yield);

现在,调用 Indexer::Index(..) 的其他类是:

enumerator indexer = p_indexer->Index(&fmap);
indexer(do_something_with_index);

bool do_something_with_index(Index* idx) {
   return condition = true; // some conditional logic
}

关于c++ - 函数如何返回指向带有函数的函数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41524745/

相关文章:

c++ - "error: conversion from ' 整数 ' to non-scalar type ' 坐标 ' requested"

c++ - VC++ 2008下qtwinmigrate + qtpropertybrowser的编译组合

c++ - 使用 shared_ptr 作为输出参数

c++ - 将 nullptr 分配给函数指针变量是否安全?

c - 对于函数指针 "fptr",为什么 "fptr"和*fptr的值相同?*fptr到底是什么意思?我只知道(*fptr)()或fptr()

c - 如何使用指针将值输入到结构中?

c++ - 从 gdb 设置 std::string 变量值?

c++ - sqlite中的文本挖掘

c++ - 如何从二进制数据调用函数

c - 如何自动初始化函数指针数组?