I implemented a class filtered_ostream_iterator that helps to filter stream using predicate and I made it as a template class.
template<typename T, typename Pred>
class filtered_ostream_iterator
{
ostream& os;
Pred _filter;
public:
filtered_ostream_iterator(ostream & o, Pred filter): os(o),
_filter(filter) {}
filtered_ostream_iterator& operator++()
{
return *this;
}
filtered_ostream_iterator& operator*()
{
return *this;
}
filtered_ostream_iterator& operator=(T t)
{
if (_filter(t))
os << t;
return *this;
}
};
It’s ok but now I have a problem. When I use filtered_ostream_iterator I have to define it in following way.
stringstream ss1;
auto filter = [](char t){ return (t >= 'a' && t <= 'z') || (t >= 'A' && t <= 'Z'); };
filtered_ostream_iterator<char, bool (*)(char)> it1(ss1, filter); // initialization
It looks not really good especially <char, bool (*)(char)>. Then I decided to make a special function that can automatically inference types.
template<typename Pred>
filtered_ostream_iterator<char, Pred> create_filtered_ostream_iterator(ostream& os, Pred pred)
{
return filtered_ostream_iterator<char, Pred>(os, pred); // problem
}
And I use it in following way
auto it1 = create_filtered_ostream_iterator(ss1, filter);
You can see that I should specify type of elements in stream and now it’s not a template actually, but when I’m trying to replace the code below with some thing like this
template<typename Pred, typename T>
filtered_ostream_iterator<T, Pred> create_filtered_ostream_iterator(ostream& os, Pred pred)
{
return filtered_ostream_iterator<T, Pred>(os, pred); // error
}
And when I’m using it in the same way
auto it1 = create_filtered_ostream_iterator(ss1, filter);
I’m getting the following error.
error: no matching function for call to 'create_filtered_ostream_iterator'
So how should I avoid all these problems? Or should I use my first variant of definition and don’t mind how hard it looks? What do you think about it?
Write it like this:
Usage:
Only trailing template arguments can be deduced, but you’re free to specify as many initial arguments as you like.
The alternative is to deduce the type from the stream:
Usage: