Вопрос

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

Boost iterator range will allow you to decorate a pair of iterators with begin/end pair (Forward Range concept):

http://www.boost.org/doc/libs/1_55_0/libs/range/doc/html/range/reference/utilities/iterator_range.html

Другие советы

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(), ...);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top