One template function that can accept two lists of any types

Viewed 195

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!

2 Answers
Related