Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ local class as functor

Tags:

c++

I am trying to use a local class as a functor and get compiler error using g++ (3.4.6).

Placing the below class ( Processor ) in the global scope resolves the error, so I guess the error is because of function local structures/classes. I would prefer to have the classes inside the function for code clarity and ease of use. Want to know if there is a workaround solution to make the below code working.

test.cpp:24: error: no matching function for call to \u2018foreachArg(int&, char*&, processSubs(int, char*)::Processor&)\u2019

template <class Functor>
void foreachArg(int n, char *args[], Functor& f)
{
    for(int i=0; i<n; ++i)
        f(args[i]);
}

int processSubs(int argc, char *args[])
{
    class Processor
    {
        public:
            void operator()(const char *arg)
            {
            }
    };

    Processor p;
    foreachArg(argc, args, p);
}

int main(int argc, char *argv[])
{
    processSubs(argc, argv);
}
like image 767
Shanky Avatar asked Mar 19 '12 14:03

Shanky


1 Answers

In C++, prior to C++11, classes used as arguments to template functions must have external linkage. Local classes don't have external linkage so you can't use them this way.

C++11 changes this, so you may be able to fix this by setting your compiler to use C++11.

like image 75
bames53 Avatar answered Sep 24 '22 12:09

bames53