Hovnatan Karapetyan
Hovnatan Karapetyan

Reputation: 57

function templates

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

Answers (2)

Dave
Dave

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

Qaz
Qaz

Reputation: 61900

A template is like a blueprint. There could be many myfunctions, 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

Related Questions