If I write a library, and I have a function that should return a sequence of values, I could do something like:
std::vector<int> get_sequence();
However, for this, the library user needs to use the std :: vector <> container, and not allow them to use any container that they want to use. In addition, it can add an additional copy of the returned array (depending on whether the compiler can optimize it or not), which can adversely affect performance.
Theoretically, you can allow the use of arbitrary containers (and avoid unnecessary additional copying) by creating a template function that starts and ends it:
template<class T_iter> void get_sequence(T_iter begin, T_iter end);
Then the function will save the sequence values ββin the range specified by iterators. But the problem is that this requires knowing the size of the sequence so that you have enough elements between begin and end to save all the values ββin the sequence.
I thought of an interface, for example:
template<T_insertIter> get_sequence(T_insertIter inserter);
which requires the T_insertIter to be an insert iterator (e.g. created using std::back_inserter(my_vector) ), but this seems too easy to use because the compiler would happily accept an iterator without insert, but would behave incorrectly at runtime.
So, is there a best practice for developing common interfaces that return sequences of arbitrary length?