Search code examples
c++templateslambdac++14generic-lambda

Template functions versus named lambdas with auto parameters


What are the differences between

template <typename T> void func( T t ) { /* ... */ }

and the C++14 alternative using lambdas with auto parameters?

auto func = []( auto t ) { /* ... */ }

Which one should be preferred?


Solution

  • The first is a function template. It can be specialized and overloaded. It can be found by ADL. When you want to take the address, you must either explicitly give it template parameters or do it in a context where the compiler can deduce them.

    The second, assuming it appears on namespace scope, is a global object with a templated function call operator. It cannot be specialized or overloaded (global variables conflict with functions, they don't overload them). It cannot be found by ADL (ADL only finds functions and function templates). If you use the address operator on it, you get the address of the object, which is pretty useless. The object itself can be converted to a function pointer if the compiler can deduce the arguments; you cannot supply them explicitly.

    You can use whichever you want; just be aware of the advantages and disadvantages of either choice. I would recommend the first. The only advantage of the second is its terseness, and I hope we'll get terse syntax for function templates in the not-too-distant future as well.

    auto func(auto t) { ... }