C ++本地类作为函子 [英] C++ local class as functor

查看:147
本文介绍了C ++本地类作为函子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用本地类作为函子,并使用g ++(3.4.6)获取编译器错误。

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

放置下面的类c> Processor )解析错误,所以我猜测错误是因为函数局部结构/类。我更喜欢有在函数内的代码清晰和易于使用的类。

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:没有匹配函数调用\ u2018foreachArg(& amp; char *& processSubs(int,char * ):: Processor&)\\\’

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


推荐答案

++ 11,用作模板函数的参数的类必须具有外部链接。本地类没有外部链接,所以你不能用这种方式。

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改变了这一点,所以你可以通过设置你的编译器使用C ++ 11。

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

这篇关于C ++本地类作为函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆