Reputation: 2610
I'm experimenting and trying to make a function that will accept two lists: one list of floats, one list of ints. My first approach is this:
template<typename FloatIterator, typename IntIterator>
Thing *createThing(
FloatIterator floatsBegin,
FloatIterator floatsEnd,
IntIterator intsBegin,
IntIterator intsEnd
) {
...
}
This works well for all sorts of containers, and even plain pointers. However, I can't easily pass in an std::initializer_list. For example, I wanted to be able to call the function like this:
Thing *thing = createThing({ 3.0, 4.0, 5.0 }, { 0, 1, 2, 2, 3, 0 });
So I'm thinking, I'll try something like this:
template<typename FloatContainer, typename IntContainer>
Thing *createThing(const FloatContainer &floats, const IntContainer &ints) {
for (float f : floats) { ... }
for (int i : ints) { ... }
}
This works well for stl containers and initializer_lists alike, but it no longer works for simple pointers. I can no longer do this:
int numFloats;
float *floats = readFloatsFromFile(&numFloats, "myfloats.txt");
int numInts;
int *ints = readIntsFromFile(&numInts, "myints.txt");
Thing *thing = createThing(floats, floats + numFloats, ints, ints + numInts);
So my question: Is there a way to write one function that can accept all three kinds of input? (pointers, stl containers, and initializer_lists)
Thanks!
Upvotes: 6
Views: 235
Reputation:
I would not even attempt to unify the two functions. Even the number of template parameters are the same, each function takes a different amount of arguments. Hence, have two function and forward:
template<typename FloatIterator, typename IntIterator>
Thing *createThing(
FloatIterator floatsBegin,
FloatIterator floatsEnd,
IntIterator intsBegin,
IntIterator intsEnd
) {
...
}
template<typename FloatContainer, typename IntContainer>
inline Thing *createThing(const FloatContainer &floats, const IntContainer &ints) {
return createThing(FloatContainer.begin(), ...);
}
Upvotes: 2
Reputation: 51465
Boost iterator range will allow you to decorate a pair of iterators with begin/end pair (Forward Range concept):
Upvotes: 1