In my project, I want to split stream into some given type of values, so I implement a template function as
template <typename TElem, typename TOutputIter>
TOutputIter SplitSpace(std::istream& IS, TOutputIter result)
{
TElem elem;
while (IS >> elem)
{
*result = elem;
++result;
}
return result;
}
I think this is awkward since I have to explicitly given the type of TElem
when calling it. For example, I have to write:
std::vector<int> v;
SplitSpace<int>(std::cin, back_inserter(v));
// I want to it to be SplitSpace(std::cin, back_inserter(v));
I tried to obtain the value type from an (template) iterator and used std::iterator_traits
as follows:
template <typename TOutputIter>
TOutputIter SplitSpace(std::istream& IS, TOutputIter result)
{
typename std::iterator_traits<TOutputIter>::value_type elem;
while (IS >> elem)
{
*result = elem;
++result;
}
return result;
}
However, the above codes do not work for back_insert_iterator
. I checked the source codes of back_insert_iterator/front_insert_iterator/insert_iterator
in std
namespace and found the value_type/difference_type/pointer/reference
are all void
.
I would like to know why these types are all void
, is there any consideration for this? Another question is that is it possible to implement the SplitSpace
function without explicitly giving the element type when call it? Thanks.
AFAIK, you should be able to obtain the
container_type
from the iterator, from which you should be able to obtain avalue_type
. You probably want to specialize for apair
at some point. This should answer part two, as for part one; not sure...