What's wrong with this (simple) lambda function?

Viewed 389

There's something wrong with the captured variable, but I can't figure out what. The error I'm getting is

error: no matching function for call to ‘applyFunc(int, main()::<lambda(int)>)’
  applyFunc<int,int>(0,[=](int z) -> int{return z + xx;}); //error!

Any insight on what's wrong?

//given input x and function func, return func(x)
template <typename T, typename U>
U applyFunc( T x, U func(T) )
{
    return func(x);
}

int main()
{
    int xx = 2;
    applyFunc<int,int>(0,[](int x) -> int {return x + 1;}); //no error
    applyFunc<int,int>(0,[=](int z) -> int{return z + xx;}); //error!

    return 0;
}

EDIT: Fix with function object from < functional >.

#include <functional>

template <typename RET, typename INPUT>
RET applyFunc( INPUT x, std::function<RET(INPUT)> func )
{
    return func(x);
}

int aFunc(int x)
{
    return x;
}

int main()
{
    int xx = 4;
    applyFunc<int,int>(0,[](int x) -> int {return x + 1;});
    applyFunc<int,int>(0,[=](int z) -> int{return z + xx;});

    return 0;
}
3 Answers
Related