2016-05-12 15 views
5

Mam powielony kod, w którym czytam z dwóch strumieni,Dla pętli zasięgu dla typu bez możliwości kopiowania, czy jest to możliwe?

{ 
std::ifstream ifs("A.dat"); 
... code ... 
} 
{ 
std::ifstream ifs("B.dat"); 
... same code ... 
} 

chciałem zjednoczyć zarówno w jednej pętli. Pierwszą reakcją jest, aby to zrobić:

for(auto ifs : {ifstream("A.dat"), ifstream("B.dat")}) 
{ 
... code ... 
} 

Jednak to nie skompilować, ponieważ typ nie jest copyable, więc próbowałem to:

for(auto& ifs : {ifstream("A.dat"), ifstream("B.dat")}) 
{ 
... code ... 
} 

że nie działa, ponieważ ifs w kasecie pętla to const. (A const ifstream nie może być używany.) to nie działało, myślę, że z tego samego powodu:

for(auto&& ifs : {ifstream("A.dat"), ifstream("B.dat")}) 

Na koniec oczywiście skończyło się to robi.

#include<iostream> 
int main(){ 
for(auto& name : {"A.dat", "B.dat"}) 
{ 
    std::ifstream ifs(name); 
    ... code ... 
} 

Ale wciąż jestem ciekawy, czy możliwe jest, aby zakres dla pętli bezpośrednio z typem jak std::ifstream?

+0

Spójrz iteratory strumieniowych, choć zwątpienie wahało się - bo bardzo ci pomoże bez brzydkich hax –

+0

@LightnessRacesinOrbit, hacki, tak, znalazłem, że mogłem 'const_cast' zmienną for-loop, która jest już dość brzydka. – alfC

+0

'Initializer_list' zezwala tylko na dostęp' const' do swoich elementów, więc nie możesz robić tego, czego chcesz, bez uciekania się do jakiejś brzydoty gdzieś. – Praetorian

Odpowiedz

5
std::ifstream streams[2]; 

streams[0].open("A.dat"); 
streams[1].open("B.dat"); 

for (auto &stream:streams) 
{ 
    // ... 
} 
+0

'std :: ifstream strumienie [] {std :: ifstream (" A.dat "), std :: ifstream (" B.dat ")} ; for (auto & stream: streams) {} ' – Praetorian

+0

To mi się przydarzyło, że użycie' std :: array' również będzie działać. Zobacz moją odpowiedź. – alfC

0

Zainspirowany użytkownika @ SamVarshavchik odpowiedź Okazało się, że to działa:

for (auto& ifs: std::array<std::ifstream, 2>{std::ifstream("A.dat"), std::ifstream("B.dat")}) 
{ 
    // ... 
} 

Z std::make_array z TS2 (http://en.cppreference.com/w/cpp/experimental/make_array) to będzie działać zbyt:

for (auto& ifs: std::make_array(std::ifstream("A.dat"), std::ifstream("B.dat"))) 
{ 
    // ... 
} 

I z dalszym siekać

template < class TT, class... Types> 
constexpr std::array<TT, sizeof...(Types)> make_array_of(Types&&... t) { 
    return {TT(std::forward<Types>(t))... }; 
} 

mogę zrobić

for (auto& ifs: make_array_of<std::ifstream>("A.dat", "B.dat")){ 
... 
} 
1

w C++, wszystko jest możliwe.

Wyobraź sobie możliwość iterator zbiór wszelkiego rodzaju strumienia, jak poniżej:

int main() 
{ 
    std::string buffer; 
    for (auto& stream : streams(std::istringstream("hello world"), 
           std::istringstream("funky chicken"), 
           std::ifstream("foo.txt"))) 
    { 
     while (stream >> buffer) 
     { 
      std::cout << buffer << std::endl; 
     } 
    } 
} 

No to teraz możesz. Oto: polimorficzny tymczasowy kontener i iterator dla każdego istream.

Podobna technika będzie działać w przypadku dowolnego zbierania obiektów, które mają wspólny interfejs polimorficzny.

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <utility> 
#include <tuple> 
#include <array> 


namespace detail { 

    template<class Interface> 
    struct iface_iter 
    { 
     using value_type = Interface; 
     using reference = Interface&; 

     using internal_p = value_type * const *; 

     iface_iter(internal_p pp) : _pp(pp) {} 

     reference operator*() const { 
      return **_pp; 
     } 

     iface_iter& operator++() { 
      ++_pp; 
      return *this; 
     } 

     bool operator==(const iface_iter& r) const { 
      return _pp == r._pp; 
     } 

     bool operator!=(const iface_iter& r) const { 
      return !(*this == r); 
     } 

     internal_p _pp; 
    }; 

    template<class CommonType, class...Streams> 
    struct common_sequence 
    { 
     using common_type = CommonType; 
     using iterator = iface_iter<common_type>; 

     constexpr static std::size_t size() { return sizeof...(Streams); } 

     using storage_type = std::tuple<Streams...>; 
     using pointer_array = std::array<common_type*, size()>; 

     common_sequence(Streams...streams) 
     : _storage(std::move(streams)...) 
     , _pointers(build_pointers(std::make_index_sequence<size()>(), _storage)) 
     {} 

     common_sequence(common_sequence&& r) 
     : _storage(std::move(r._storage)) 
     , _pointers(build_pointers(std::make_index_sequence<size()>(), _storage)) 
     { 
     } 

     common_sequence& operator=(common_sequence&& r) 
     { 
      _storage = std::move(r._storage); 
      _pointers = build_pointers(std::make_index_sequence<size()>(), _storage); 
     } 

     template<std::size_t I> 
     using stream_type = std::tuple_element_t<I, storage_type>; 


     template<std::size_t...Is> 
     static constexpr 
     pointer_array build_pointers(std::index_sequence<Is...>, 
            std::tuple<Streams...>& tup) 
     { 
      return pointer_array { 
       static_cast<common_type*>(&static_cast<stream_type<Is>&>(std::get<Is>(tup)))... 
      }; 
     } 

     iterator begin() const { 
      return { _pointers.data() }; 
     } 

     iterator end() const { 
      return { _pointers.data() + size() }; 
     } 

     mutable storage_type _storage; 
     pointer_array _pointers; 

    }; 

} 

template<class CommonBase, class...Things> 
auto make_common_sequence(Things&&...ts) 
{ 
    return detail::common_sequence<CommonBase, std::decay_t<Things>...>(std::move(ts)...); 
} 

template<class...Streams> 
auto streams(Streams&&...strs) 
{ 
    return make_common_sequence<std::istream>(std::move(strs)...); 
} 

struct base 
{ 
    virtual void foo() = 0; 
}; 

struct d1 : base 
{ 
    void foo() override { std::cout << "d1::foo" << std::endl; } 
}; 

struct d2 : base 
{ 
    void foo() override { std::cout << "d2::foo" << std::endl; } 
}; 

template<class...Ts> 
auto bases(Ts&&...ts) 
{ 
    return make_common_sequence<base>(std::move(ts)...); 
} 


int main() 
{ 
    std::string buffer; 
    for (auto& stream : streams(std::istringstream("hello world"), 
           std::istringstream("funky chicken"), 
           std::ifstream("foo.txt"))) 
    { 
     while (stream >> buffer) 
     { 
      std::cout << buffer << std::endl; 
     } 
    } 

    for (auto& f : bases(d1(), d2(), d1(), d2())) 
    { 
     f.foo(); 
    } 

    return 0; 
} 

oczekiwany wynik:

hello 
world 
funky 
chicken 
... plus whatever is in foo.txt ... 
d1::foo 
d2::foo 
d1::foo 
d2::foo 

Oczywiście, jeśli nie wymagają polimorfizm, prosty szablon o zmiennej liczbie argumentów iterator argumentem wystarczą:

template<class F, class...Things> 
void apply_to_all(F f, Things... things) 
{ 
    using expand = int[]; 
    void(expand{ 0, 
     (f(things), 0)... 
    }); 
} 

int main() 
{ 
    std::string buffer; 
    apply_to_all([&](auto& stream) 
       { 
        while (stream >> buffer) 
        { 
         std::cout << buffer << std::endl; 
        } 
       }, 
       std::istringstream("hello world"), 
       std::istringstream("funky chicken"), 
       std::ifstream("foo.txt")); 
} 
+0

Fajnie, to wykracza poza to, o co prosiłem (polimorfizm), ale robi wrażenie. – alfC

+0

To jest bardzo ogólne rozwiązanie problemu z polimorficznym pojemnikiem, czy wiesz, czy możliwe jest automatyczne wykrywanie najbardziej powszechnego interfejsu (klasa 'istream' w tym przypadku)? – alfC

+0

@alfC daj mi chwilę ... –

Powiązane problemy