Can I use a lambda function or std::function object in place of a function pointer?

前端 未结 4 948
-上瘾入骨i
-上瘾入骨i 2021-02-13 21:04

I\'ve got a library that I need to use that defines the following:

typedef void CallbackFunction(const int& i);

and has a function to regis

4条回答
  •  暖寄归人
    2021-02-13 21:21

    Short Answer: No

    Long Answer:

    Lamda's are just syntactic sugar for functors.
    Functors are objects that act like functions.

    A function pointer is not the same type of thing. In general you can not use functors where you need a function pointer.

    Extra:

    On the other hand it is easy to wrap a function to become a functor.

    Historically:

    Function pointers are generally used by C libraries. As C++ libraries will use an interface to achieve the same affect. Thus you can see why it is hard to pass functors where a function pointer is requried (the C code has no way to understand how to use the functor).

提交回复
热议问题