patterncppMinor
begin and end overloads for istream_iterator
Viewed 0 times
istream_iteratorforendandoverloadsbegin
Problem
I wrote this pretty straight forward begin and end overloads for
Is this standards compliant? Any problems with usage?
istream_iterator. Is this standards compliant? Any problems with usage?
#include
#include
#include
namespace std
{
template
std::istream_iterator begin(std::istream_iterator iter)
{
return iter;
}
template
std::istream_iterator end(std::istream_iterator)
{
return std::istream_iterator();
}
}
int main()
{
for (std::string s : std::istream_iterator(std::cin))
{
std::cout << s;
}
}Solution
Not sure that's how I would have written in.
Its not normal to call
I would have arranged for a some type to represent the stream as a container:
Its not normal to call
std::begin() and std::end() on an iterator.I would have arranged for a some type to represent the stream as a container:
#include
#include
#include
namespace ThorsAnvil
{
template
struct StreamAsContainer
{
std::istream& str;
StreamAsContainer(std::istream& str) : str(str) {}
};
template
std::istream_iterator begin(StreamAsContainer& c)
{
return std::istream_iterator(c.str);
}
template
std::istream_iterator end(StreamAsContainer&)
{
return std::istream_iterator();
}
}
int main()
{
namespace TA=ThorsAnvil;
for (std::string s : TA::StreamAsContainer(std::cin))
{
std::cout << s;
}
}Code Snippets
#include <iostream>
#include <iterator>
#include <fstream>
namespace ThorsAnvil
{
template<typename T>
struct StreamAsContainer
{
std::istream& str;
StreamAsContainer(std::istream& str) : str(str) {}
};
template <typename T>
std::istream_iterator<T> begin(StreamAsContainer<T>& c)
{
return std::istream_iterator<T>(c.str);
}
template <typename T>
std::istream_iterator<T> end(StreamAsContainer<T>&)
{
return std::istream_iterator<T>();
}
}
int main()
{
namespace TA=ThorsAnvil;
for (std::string s : TA::StreamAsContainer<std::string>(std::cin))
{
std::cout << s;
}
}Context
StackExchange Code Review Q#105050, answer score: 4
Revisions (0)
No revisions yet.