Jump to content
  • Advertisement
Sign in to follow this  
dmatter

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!