CKTIS / C++
Unary `+`: converting a captureless lambda to a function pointer
In `+hardPass`, unary `+` makes a non-generic captureless lambda use its implicit conversion to a function pointer. Changing the argument type can change which overload is selected.
Version: ISO C++23; implementation support may vary
Syntax
auto hardPass = [](int score) { return score >= 40; };
auto ptr = +hardPass; // bool (*)(int)
bool (*callback)(int) = hardPass; // The declared type supplies the target.hardPass is a closure object with its own unnamed class type. In +hardPass, + has one operand: it is unary plus, not addition. Built-in unary + accepts a function pointer and returns its value unchanged. Here the operand first converts implicitly to bool (*)(int).
So auto ptr = +hardPass; declares a pointer, while auto copy = hardPass; copies the closure. bool (*ptr)(int) = hardPass; needs no + because the declaration supplies the target type. In the example, kind(hardPass) selects the template, which matches without a pointer conversion. For kind(+hardPass), both overloads match equally well, so the non-template wins.
The conversion requires empty []: [x], [=], and [&] prevent it, even if a capture default captures nothing. Under the corrected C++23 rule, an explicit object parameter (this …) also prevents it; compiler support may vary. A generic lambda such as [](auto x) { return x; } does not yield a concrete pointer with unary + alone. You can supply a target type instead: int (*id)(int) = [](auto x) { return x; };.
The pointer preserves the parameter and return types and carries noexcept if the call operator is non-throwing. It points to a function, not to the closure, so it does not depend on the lifetime of hardPass. The function has C++ language linkage, not guaranteed extern "C" linkage.
Examples
#include <iostream>
#include <type_traits>
using Predicate = bool (*)(int);
const char* kind(Predicate) { return "function pointer"; }
template<class F>
const char* kind(F) { return "closure"; }
int main() {
auto hardPass = [](int score) { return score >= 40; };
auto ptr = +hardPass;
static_assert(std::is_class_v<decltype(hardPass)>);
static_assert(std::is_same_v<decltype(ptr), Predicate>);
std::cout << kind(hardPass) << '\n'
<< kind(+hardPass) << '\n'
<< std::boolalpha << ptr(42) << '\n';
}
Result
closure function pointer true
The first two lines show overload selection before and after conversion. The third shows the result of calling `ptr(42)`.
Related lessons
- C++ · Lesson 8 · Intermediate · Version: 2