1

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;
}
  • If it won't compile, at least give the error. – chris Mar 09 '13 at 03:17
  • Also, you might just want to include "using namespace std;" so you don't have to keep writing "std::" – Jon Rubins Mar 09 '13 at 03:19
  • 3
    @jrubins, That's generally considered [bad practice](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c). – chris Mar 09 '13 at 03:20
  • @chris I meant more for ease of use because it seems like he's just trying to write a quick program and it seems unlikely he'll use conflicting namespaces – Jon Rubins Mar 09 '13 at 03:22
  • @jrubins, True, it's particularly useful in certain situations. The sad fact is that far too many people use it 100% of the time and eventually run into problems. I try to prevent that. – chris Mar 09 '13 at 03:23
  • @chris touche. Good point – Jon Rubins Mar 09 '13 at 03:24

2 Answers2

2

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.

Dave
  • 44,275
  • 12
  • 65
  • 105
1

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>);
                                                      ^^^^^^^^
chris
  • 60,560
  • 13
  • 143
  • 205
  • but I thought that for_each() function will pass double to the myfunction() and that way myfunction() will instantiate, no? – Hovnatan Karapetyan Mar 09 '13 at 08:28
  • @HovnatanKarapetyan, The thing is, it takes a specific function, not a blueprint for functions. Each type has its own function, and you know which type you want it to use. Also, you might not always want to use the type stored in your container. Say you had to input doubles and print the greatest integer of them all. You can get your input using `std::istream_iterator` and then just copy to output using `std::ostream_iterator`. – chris Mar 09 '13 at 14:02