for_each problem with functor

This topic is 4851 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Why doesn't the following code work?:
using namespace std;

class some_class
{
vector<int> int_vector;

public:
some_class() : int_vector(5, 5) { }

void output()
{
struct print_all
{
void operator() (int& i)
{
cout << i << endl;
}
};

for_each(int_vector.begin(),
int_vector.end(),
print_all());        //Error highlighted here???
}
};


I would have expected the member-function 'output' to write 5 lines of '5' on the screen, instead I get a complaint: no matching function for call to `for_each(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, some_class::output()::print_all)' Surely enough, if I move the functor code out of the function then I have no problems, but why doesn't it work as is? I've seen code like this before (but can only assume it works since I never tried it) Maybe I'm just being stupid (probably [smile]) but I'd like to know for sure. Thanks

Share on other sites
Template parameters need to have external linkage. Objects defined inside a function have internal linkage. (Basically the answer is because the standard says it shouldn't work.)

Share on other sites
Thanks for the info SiCrane :)

I found an example here on GDNet from my bookmarks where similar code has been used (posted by snk_kid): search for 'for_each' and its the first hit.
Is this an exception somehow or is it wrong too?

Share on other sites
that example do looks awfully dubious, I would say that it shoulnd't compile.

Share on other sites
If you prefer C# style for_each keyword (ie. no need to write minimalistic and pointless functors), then here's a supposedly robust implementation of one for C++: C++ Source: Foreach"

1. 1
Rutin
32
2. 2
3. 3
4. 4
5. 5

• 13
• 9
• 9
• 9
• 14
• Forum Statistics

• Total Topics
633324
• Total Posts
3011369
• Who's Online (See full list)

There are no registered users currently online

×