1

Here are a couple of snippets from my first successful use of the std::for_each() construct:

struct add_to_memory {
    void operator()(const boost::tuple<const string&, const string&> &t ) {
        m_map.insert(make_pair(t.get<0>(),t.get<1>()));
    }
    add_to_memory(MemoryBank &m) : m_map(m) {};
private:
    MemoryBank &m_map;
};

void
memorize(Block &block) {
    block.get_record_types(record_type_set);
    BOOST_FOREACH(D_RecordType_Set::value_type rec_type, record_type_set) {
        MD_Zip_Range zipper = block.make_field_value_zip_range(rec_type);
        std::for_each(zipper.first, zipper.second, add_to_memory(memory_bank));
    }
}

I now want to change "memorize" into a function that accepts an additional parameter - a function or functor or whatever it is add_to_memory() is. But I can't figure out what type to use in the signature.

void scan_block_and_apply_function( Block&, ..?.. );

I'm using [read: "stuck with"] g++ 4.4, so it's safe to say I haven't got c++11. What should the signature be? And how should scan_block_and_apply_function() be called?

4

3 回答 3

2

这通常通过模板完成:

template <typename MemoryBankFunctor>
void memorize(Block &block, MemoryBankFunctor functor) {
    block.get_record_types(record_type_set);
    BOOST_FOREACH(D_RecordType_Set::value_type rec_type, record_type_set) {
        MD_Zip_Range zipper = block.make_field_value_zip_range(rec_type);
        std::for_each(zipper.first, zipper.second, functor);
    }
}
于 2013-08-12T19:38:01.970 回答
0

What you're passing is an instance of add_to_memory. So something like this should do:

void memorize(Block &block, add_to_memory func)
{
    // ...
    std::for_each(zipper.first, zipper.second, func);
}
于 2013-08-12T19:33:36.657 回答
0

您应该使用模板化参数:



    template <typename T>
    void scan_block_and_apply_function( Block&, const T& );


这将允许您使用任何类型的仿函数或函数

于 2013-08-12T19:38:16.227 回答