函数如何返回指向函数的函数?

时间:2017-01-07 18:06:51

标签: 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*))}'

我的声明中缺少什么?

1 个答案:

答案 0 :(得分:0)

Indexer.hpp中,typedef需要告诉编译器enumeratorIndexer成员方法:

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