Reputation: 57
can you please help me to understand why this code doesn't compile? I'm trying to understand C++ templates.
#include <iostream>
#include <algorithm>
#include <vector>
template <class myT>
void myfunction (myT i)
{
std::cout << ' ' << i;
}
int main ()
{
double array1[] = {1.0, 4.6, 3.5, 7.8};
std::vector<double> haystack(array1, array1 + 4);
std::sort(haystack.begin(), haystack.end());
std::cout << "myvector contains:";
for_each (haystack.begin(), haystack.end(), myfunction);
std::cout << '\n';
return 0;
}
Upvotes: 1
Views: 66
Reputation: 46249
Because you're passing myfunction
to a function, it can't work out which template to use automatically, so you have to tell it with myfunction<double>
This doesn't apply when calling it directly, like myfunction(2.0)
because as a convenience, the compiler will figure out which template to use based on the parameters you give it.
Upvotes: 2
Reputation: 61900
A template is like a blueprint. There could be many myfunction
s, each taking a different type. You have to give the type when you instantiate it in this case to tell the compiler which one to use:
for_each (haystack.begin(), haystack.end(), myfunction<double>);
^^^^^^^^
Upvotes: 1