C++ 编译器错误 C3493:无法隐式捕获“func”,因为未指定默认捕获模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4315862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:06:17  来源:igfitidea点击:

Compiler error C3493: 'func' cannot be implicitly captured because no default capture mode has been specified

c++visual-studiovisual-studio-2010c++11compiler-errors

提问by Thomas Bonini

Can you help me resolve this compiler error?

你能帮我解决这个编译器错误吗?

template<class T>
static void ComputeGenericDropCount(function<void(Npc *, int)> func)
{
    T::ForEach([](T *what) {
        Npc *npc = Npc::Find(what->sourceId);

        if(npc)
            func(npc, what->itemCount); // <<<<<<< ERROR HERE
            // Error    1   error C3493: 'func' cannot be implicitly captured because no default capture mode has been specified

    });
}

static void PreComputeNStar()
{
     // ...
    ComputeGenericDropCount<DropSkinningNpcCount>([](Npc *npc, int i) { npc->nSkinned += i; });
    ComputeGenericDropCount<DropHerbGatheringNpcCount>([](Npc *npc, int i) { npc->nGathered += i; });
    ComputeGenericDropCount<DropMiningNpcCount>([](Npc *npc, int i) { npc->nMined += i; });
}

I can't understand why it's giving me the error and I don't know how to fix it. ComputeGenericDropCount(auto func)doesn't work either.

我不明白为什么它给我错误,我不知道如何解决它。ComputeGenericDropCount(auto func)也不起作用。

回答by ronag

You need to specify how to capture funcinto the lambda.

您需要指定如何捕获func到 lambda 中。

[]don't capture anything

[]不要捕捉任何东西

[&]capture-by-reference

[&]按引用捕获

[=]capture-by-value (copy)

[=]按值捕获(复制)

T::ForEach([&](T *what) {

I'd also recommend that you should send funcby const reference.

我还建议您应该func通过常量引用发送。

static void ComputeGenericDropCount(const function<void(Npc *, int)>& func)