likern
likern

Reputation: 3974

Type conversion iterator in C++

I have type SDK::TIPAddressDescription which I don't control and my THNNetIface which is also not controlled enough by me as is generated from IDL specification. Also I've wrapped types by iterators to make them workable with STL.

I want to add modifications to existing code:

// Update IP addresses of interfaces existing in DB
vector<THNNetIface> modIfaces;
set_intersection(ifaceFirstIter, ifaceLastIter, ipFirstIter, ipLastIter, 
    back_inserter(modIfaces), HNInfoComparator());

with the following:

// Note: delIfaces is not of type SDK::TIPAddressDescription as expected by STL;
vector<THNNetIface> delIfaces;
set_difference(ipFirstIter, ipLastIter, ifaceFirstIter, ifaceLastIter,
    mod_inserter(delIfaces), HNInfoComparator());

where mod_iterator acts as converter from SDK::TIPAddressDescription type to THNNetIface for each element (to satisfy STL requirements) and back_inserter at the same time (or compatible with them).

How to do this type-convertion iterator? Is there existing approaches to do that in Boost-similar libraries?

Upvotes: 2

Views: 126

Answers (1)

sehe
sehe

Reputation: 393769

Yes, Boost Iterator and Boost Range have facilities that do this.

  • The most generic is boost::function_output_iterator

    Live On Coliru (c++03)

    auto output = boost::make_function_output_iterator(
            phx::push_back(phx::ref(delIfaces), phx::construct<THNNetIface>(arg1)));
    
    boost::set_difference(iface, ip, output, HNInfoComparator());
    

    OR

    Live On Coliru (c++11)

    auto output = boost::make_function_output_iterator(
            [&](TIPAddressDescription const& ip) { delIfaces.emplace_back(ip); });
    
    boost::set_difference(iface, ip, output, HNInfoComparator());
    

  • Boost Range transformed perhaps with boost::phoenix::construct<> could be more elegant Sadly this option is not available, since set_difference requires an output iterator. This was a thinko

Upvotes: 1

Related Questions