39

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.

Andreas Bonini
  • 44,018
  • 30
  • 122
  • 156

1 Answers1

67

You need to specify how to capture func into the lambda.

[] don't capture anything

[&] capture-by-reference

[=] capture-by-value (copy)

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

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

static void ComputeGenericDropCount(const function<void(Npc *, int)>& func)
Smi
  • 13,850
  • 9
  • 56
  • 64
ronag
  • 49,529
  • 25
  • 126
  • 221
  • This doesn't work and gives me the same error; also I thought that `[]` means "capture nothing"; `[&]` means "capture all upvalues by reference, `[*]` means "capture all upvalues by copy", and so on.. But I think this only affects how upvalues are captured, ie, it will only affect code *inside* the lambda – Andreas Bonini Nov 30 '10 at 16:24
  • 1
    You need to capture func in-order to use it inside the lambda, which you do. I don't see how you could get the same error. I'll try it myself once i get home. – ronag Nov 30 '10 at 16:26
  • Sorry! I added the `&` to the wrong lambdas, the callbacks from `ComputeGenericDropCount`, instead of `ForEach`, as you said. Now everything makes sense: it needed to know how to capture func, of course!! Thanks again. – Andreas Bonini Nov 30 '10 at 16:27
  • `&` is what I need. Thanks – DawnSong Mar 02 '16 at 14:27