Shanky
Shanky

Reputation: 139

C++ local class as functor

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);
}

Upvotes: 7

Views: 1461

Answers (4)

Matthieu M.
Matthieu M.

Reputation: 299810

As has been said, using local classes for this was not possible pre-C++11, and about useless in C++11 because lambdas are less wordy.

You should simply declare your class outside the function.

Upvotes: 0

bames53
bames53

Reputation: 88155

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.

Upvotes: 9

Managu
Managu

Reputation: 9039

C++03 doesn't allow locally defined classes to be template arguments, as you've found out here. C++11 allows this. With gcc, you might try compiling with --std=c++0x

Upvotes: 0

Puppy
Puppy

Reputation: 146910

You cannot instantiate templates with local classes in C++03.

Also, the Standard already provides a function for this- std::for_each.

Upvotes: 0

Related Questions