我有一些重复的代码,我从两个流中读取,
{
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
。 (a 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
这样的类型进行for循环?
答案 0 :(得分:5)
std::ifstream streams[2];
streams[0].open("A.dat");
streams[1].open("B.dat");
for (auto &stream:streams)
{
// ...
}
答案 1 :(得分: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"));
}
答案 2 :(得分:0)
受@ SamVarshavchik的回答启发,我发现这有效:
for (auto& ifs: std::array<std::ifstream, 2>{std::ifstream("A.dat"), std::ifstream("B.dat")} )
{
// ...
}
来自TS2(http://en.cppreference.com/w/cpp/experimental/make_array)的std::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") ){
...
}