When should an API use a function pointer, templated callable, lambda or functor, or std::function, and what trade-offs follow for state, lifetime, allocation, and optimization?
Show answer and explanation
A raw function pointer is small, nullable, and ABI-friendly for free or static functions, but it cannot directly own captured state. A lambda or named functor is a concrete object whose type carries state and whose operator() can often be inlined; callers must still ensure that referenced captures outlive every invocation. A template parameter accepts arbitrary callable types without type erasure and exposes them to optimization, at the cost of template instantiations, header-visible implementation, and possible code-size growth. std::function provides a copyable type-erased wrapper with one stable signature and is useful for stored callbacks or heterogeneous callables, but invocation is indirect and the target may allocate; calling an empty wrapper throws bad_function_call. Reference wrappers and non-owning callable views need explicit lifetime contracts. Choose from ownership, nullability, storage duration, ABI, copyability, hot-path measurement, and whether the callable must be stored heterogeneously.
A raw function pointer is small, nullable, and ABI-friendly for free or static functions, but it cannot directly own captured state. A lambda or named functor is a concrete object whose type carries state and whose operator() can often be inlined; callers must still ensure that referenced captures outlive every invocation. A template parameter accepts arbitrary callable types without type erasure and exposes them to optimization, at the cost of template instantiations, header-visible implementation, and possible code-size growth. std::function provides a copyable type-erased wrapper with one stable signature and is useful for stored callbacks or heterogeneous callables, but invocation is indirect and the target may allocate; calling an empty wrapper throws bad_function_call. Reference wrappers and non-owning callable views need explicit lifetime contracts. Choose from ownership, nullability, storage duration, ABI, copyability, hot-path measurement, and whether the callable must be stored heterogeneously.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.