Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it bad to have a local functor?

For example, whats wrong with declaring the class doubler within the main function, if the predicate will only be used once?

#include <list>
#include <algorithm>
#define SIZE 10
int main()
{
    std::list<int> myList;
    for(int i=0; i<SIZE ;++i)
    {
        myList.push_back(i);
    }

    class doubler
    {
    public:
        doubler(){}
        int operator()(int a)
        {
            return a + a;
        }

    } pred;

    std::for_each(myList.begin(), myList.end(), pred);
    return 0;
}
like image 306
aCuria Avatar asked Jan 03 '11 08:01

aCuria


2 Answers

The problem with this setup is that, at least in C++03, you cannot use a local functor as a template argument because it doesn't have external linkage. This means that technically speaking, the above code isn't legal. However, they're fixing this in C++0x since it's a pretty silly restriction, and since VS2010 has rudimentary C++0x support the above code is totally fine.

In short, the answer to your question is that there's nothing wrong with it if you're using C++0x-compliant compilers, but otherwise you should probably refrain from doing so to maximize cross-compiler compatibility.

like image 121
templatetypedef Avatar answered Sep 17 '22 20:09

templatetypedef


  • It is illegal before C++0x
  • In C++0x, there is a better solution (lambdas/closures)

So in either case you should use a different solution.

like image 37
Konrad Rudolph Avatar answered Sep 21 '22 20:09

Konrad Rudolph