How I can pass lambda expression to c++ template as parameter

后端 未结 4 1883
北海茫月
北海茫月 2020-12-31 08:03

I have a template that accepts a function as an argument.

When I try to pass a lambda expression it does not compile.

typedef int (*func)(int a);
te         


        
4条回答
  •  长情又很酷
    2020-12-31 08:45

    This is because the lambda as its own type.
    You have templatize function() on the type of the function passed.

    template
    int function(F foo, int a) {
        return foo(a);
    }
    
    int test(int a) {
        return a;
    }
    
    int main()
    {
        // function will work out the template types
        // based on the parameters.
        function(test, 1);
        function([](int a) -> int { return a; }, 1);
    }
    

提交回复
热议问题