我读过这个问题 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/