2017-01-07 42 views
2

我读过这个问题How to make a function return a pointer to a function? (C++)函数如何返回指向函数的函数?

...但我仍然有问题。 Index函数返回一个枚举器函数,该函数接受一个函数,将其生成每个索引。该函数签名已经typedef版在Indexer.hpp:

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

我有问...为什么你在这里让生活如此困难?什么是所有的函数指针? –

+2

指向非成员函数的指针与指向成员函数的指针不同。区别在于指向非成员函数的指针不需要调用对象,但指向成员函数的指针可以。我建议你阅读['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)和['std :: bind'](http:// en。 cppreference.com/w/cpp/utility/functional/bind)。 –

+0

另外你现在应该知道我们期望在这里有一个[MCVE]。这段代码中有大量未提及的类型。 –

回答

0

Indexer.hpptypedef需要告诉编译器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 
}