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.
You cannot do it. However, in some cases, you can use
boost::bindorboost::lambdalibraries 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; });