Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define a functor inside a function

Tags:

c++

Sometimes, I need some functor-helper to manipulate list. I try to keep the scope as local as possible.

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    struct Square
    {
        int operator()(int x)
        {
            return x*x;
        }
    };

    int a[5] = {0, 1, 2, 3, 4};
    int b[5];

    transform(a, a+5, b, Square());

    for(int i=0; i<5; i++)
        cout<<a[i]<<" "<<b[i]<<endl;
}

hello.cpp: In function ‘int main()’:
hello.cpp:18:34: error: no matching function for call to ‘transform(int [5], int*, int [5], main()::Square)’

If I move Square out of main(), it's ok.

like image 397
kev Avatar asked Jul 30 '11 14:07

kev


1 Answers

You cannot do it. However, in some cases, you can use boost::bind or boost::lambda libraries to build functors without declaring an outside structure. Also, if you have a recent compiler (such as gcc version 4.5) you can enable the new C++0x features which allow you to use lambda expressions, allowing such syntax:

transform(a, a+5, b, [](int x) -> int { return x*x; });

like image 56
neodelphi Avatar answered Oct 11 '22 06:10

neodelphi