Returning std::list trough an iterator NOT using templates
refering to this answer, the second code block. My question is:
If I know I will be processing only std::lists<int>
, and only <int>
.
Is there a way to write this (the second block and the third one) without using templates and without passing the list by reference as suggested in the comments? Could you show it to me?
I think it makes sense to avoid using t开发者_如何转开发emplates if the implementation only covers one single type right??? ( or am I too lazy? )
That's my answer!
You can pass a std::back_insert_iterator<std::list<int> >
to a function with or without templates. Secretly, you're still passing the list by reference, since the iterator itself holds a reference or pointer to the container.
typedef std::back_insert_iterator<std::list<int> > OutputIterator;
void getInts(OutputIterator out) {
for (int i = 0; i < 10; ++i) {
*(out++) = i;
}
}
Then the caller does:
std::list<int> l;
getInts(std::back_inserter(l));
You're still "using templates" in the sense that back_inserter
is a function template, and back_insert_iterator
is a class template, but then again so is list
. This way you aren't writing any templates of your own.
I disagree that it necessarily makes sense to avoid templates if you're only interested in one type -- a side-effect of C++ templates is type inference via template argument deduction, meaning that you don't have to write out ridiculous types like std::back_insert_iterator<std::list<int> >
, even once in a typedef. As you can see from the code, avoiding templates isn't laziness, it's actually less text to write the template precisely because you don't have to mention the types. But if for some reason you want to go out of your way to restrict that function to only work with lists, and only with appending to the back of them, then you can go ahead.
精彩评论