2016-05-12 44 views
5

我有一些重複的代碼,這是我從兩個流讀取,對於不可複製類型的範圍循環,有可能嗎?

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

我想在一個循環統一兩者。 第一反應就是要做到這一點:

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

但是它並不能編譯,因爲類型是不可拷貝的,所以我想這:

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

不會因爲ifs內工作循環是const。 (一const ifstream不能使用。) 這也不能工作,我覺得出於同樣的原因:

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

在課程結束時,我終於實現了這一點。

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

但我仍然好奇,如果有可能有一系列的循環直接與型像std::ifstream

+0

查一查流迭代器,雖然我懷疑遠距離爲你提供幫助而不會感到醜陋hax –

+0

@LightnessRacesinOrbit,hacks,是的,我發現我可以'const_cast' for循環變量,這已經很醜了。 – alfC

+0

一個'initializer_list'只允許'const'訪問它的元素,所以如果不在某個地方使用某種醜陋的東西,你就無法做到你想要的東西。 – Praetorian

回答

5
std::ifstream streams[2]; 

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

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

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

+0

不錯,這讓我覺得使用'std :: array'也可以。看到我的答案。 – alfC

0

通過@ SamVarshavchik的回答啓發,我發現這工作:

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

隨着std::make_array從TS2(http://en.cppreference.com/w/cpp/experimental/make_array),這將工作太:

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

並配有進一步的黑客

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

我可以做

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

在C++中,一切皆有可能。

想象一下,能夠迭代器任何流的集合,像這樣:

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; 
     } 
    } 
} 

現在好了,你可以。注意:任何istream的多態臨時容器和迭代器。

類似的技術將適用於共享一個公共多態接口的任意對象集合。

#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; 
} 

預期輸出:

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

當然,如果我們不要求多態性,一個簡單的模板參數可變參數的迭代器就足夠了:

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

不錯,這超出了我所問(多態),但它是非常令人印象深刻。 – alfC

+0

這是一個對多態容器問題的非常通用的解決方案,你知道是否可以自動檢測最常用的接口(在這種情況下是類'istream')嗎? – alfC

+0

@alfC給我一點時間... –