[C++] for_each() gives errors C2896 & C2784

Apr 7, 2010 at 4:12am
Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

template<class T>
void squared(T &root){
  root*=root;
  cout<<" "<<root;
}

int main(){
  vector<int> v;
  for(int i=0; i<10; i++)
    v.push_back(i);
  for_each(v.begin(), v.end(), squared);

  return 0;
}


I'm learning the STL, but when I tried this, I get the errors meantioned. Compile it to see. Can anybody give some insight on this?

I'm using a template so then the type can easily be altered.

MSVC++ Express Edition in Code::Blocks
XP SP3
Apr 7, 2010 at 5:08am
The compiler can't figure out the types you're passing. Keep in mind that the definition of std::for_each is something like this:
1
2
3
4
5
template <typename Iterator,typename Function>
void for_each(Iterator begin,Iterator end,Function f){
    for (;begin!=end;++begin)
        f(*begin);
}
Notice that no type is mentioned anywhere. Iterators don't provide any information on the type that their containers hold, so if the function doesn't provide any type information, either, the compiler is left with an std::for_each() that it doesn't know how to generate code for.
Basically, it's a mutual dependency problem. Your template function depends on the types that std::for_each() will use, and std::for_each() depends on the type of parameter that your function will take.
You can break the dependency by explicitly telling the compiler to make an instance of the template function, however:
for_each(v.begin(), v.end(), squared<int>);
Apr 7, 2010 at 5:45am
can you sure the type of T?
Apr 7, 2010 at 5:08pm
That helios. Is there a way to write this to where I don't have to tell it what type I'm using, and still use a template?
Apr 7, 2010 at 6:52pm
No.
Apr 7, 2010 at 6:54pm
Thanks.
Topic archived. No new replies allowed.