I’m implementing a template function which sets the values of the first n elements of a sequence pointed to by a parameter iterator to values returned by calls to a generator function.
I have the following code:
template <typename IteratorOut, typename SizeType, typename Generator> IteratorOut createSequence(IteratorOut out, SizeType n, Generator gen) {
std::vector<Generator> vec;
for (SizeType i = 1; i <= n; i++) {
vec.push_back(gen());
}
std::copy(vec.begin(), vec.end(), out);
return out;
}
I’m testing the function with the following:
int generate () {
return 5;
}
...
std::vector<int> vec_int;
createSequence(vec_int.begin(), 5, generate);
for (std::vector<int>::iterator iter = vec_int.begin(); iter != vec_int.end(); iter++) {
std::cout << *iter << std::endl;
}
I get “error: invalid conversion from ‘int (*)()’ to ‘int’”. Can you see what’s wrong with my template function?
The type of the vector is wrong:
Here,
Generatoris a function, and you want a vector ofints instead:But maybe you don’t need a vector at all!