How to define a functor inside a function

Sometimes I need a functor helper to manipulate a list. I try to keep the area 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 from main() , that's fine.

+7
source share
4 answers

You cannot do this. However, in some cases, you can use boost::bind or boost::lambda libraries to create functors without declaring an external structure. Also, if you have a recent compiler (e.g. gcc version 4.5), you can include new C ++ 0x functions that allow you to use lambda expressions, allowing this syntax:

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

+6
source

In the current standard (C ++ 98/03) local classes (local functors) cannot be used as classes as a template parameter.

+6
source

As pointed out by several answers here, C ++ pre-0x cannot use local types as template arguments. What I usually do to get around this problem (besides the hopes that the projects I'm working on will soon switch to C ++ 0x) should put the corresponding local class as a private nested class in the member function class that needs this functor. As an alternative, I sometimes put a functor in the corresponding .cpp file, representing that it is cleaner (and compiles a little faster).

0
source

I think the best answer to this question is: "Use a functional programming language."

-one
source

All Articles