Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Unary plus: converting a lambda to a function pointer

`+hardPass` uses unary `+` to convert a captureless, non-generic lambda to a function pointer. It does not perform addition.

Version: ISO C++23; implementation support may vary

Syntax

+expression

auto hardPass = [](int score) { return score >= 60; };
auto ptr = +hardPass;          // bool (*)(int)
bool (*typed)(int) = hardPass; // same conversion, with an explicit target type

+hardPass has one operand; a + b has two. In this example, overload resolution selects the built-in unary + for pointers: the closure object is implicitly converted to a pointer, and the operator yields that same pointer value. It neither adds anything nor calls the lambda.

auto hardPass = ... stores a closure object, while auto ptr = +hardPass; deduces bool (*)(int). Calling ptr(60) gives the same result as hardPass(60). The pointer points to a function, not to the original closure object, so it does not depend on that object's lifetime. A readable alternative is bool (*ptr)(int) = hardPass;: the explicit target type makes + unnecessary.

The conversion shown for a non-generic lambda has been available since C++11. In C++23 the lambda must have no capture list other than [] and no explicit object parameter; even [=] that captures nothing is not equivalent to []. A generic lambda such as [](auto x) { return x; } can convert given a matching target type such as int (*)(int), but unary + alone does not select a concrete specialization for it.

Examples

#include <iostream>
#include <type_traits>

int main() {
    auto hardPass = [](int score) { return score >= 60; };
    auto ptr = +hardPass;

    static_assert(std::is_class_v<decltype(hardPass)>);
    static_assert(std::is_same_v<decltype(ptr), bool (*)(int)>);

    std::cout << (ptr(60) ? 1 : 0) << '\n';
    std::cout << (ptr(59) ? 1 : 0) << '\n';
}

Result

1
0

The static assertions distinguish the closure type from the function-pointer type. The calls through the pointer print `1` for a score of 60 and `0` for a score of 59.

Related lessons

  • C++ · Lesson 8 · Intermediate · Version: 2

Sources