Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Unary plus operator (+)

Unary + preserves its operand's value but can change its type through integral promotion. For an eligible noncapturing lambda, it can also force conversion to a function pointer.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

+expression

Built-in unary + accepts an operand of arithmetic, unscoped enumeration, or pointer type and produces a prvalue. It preserves the value but applies integral promotions: +true has type int and value 1. It does not mean absolute value: +(-3) remains -3.

The +lambda idiom uses noncapturing lambda conversion to function pointer. For a non-generic lambda with [] and no explicit object parameter, built-in + can use this conversion. In the example, auto fp = +twice creates an int (*)(int), not another closure object. Evaluating +twice does not call the lambda; fp(21) does.

Capturing prevents this conversion; this also applies to [=], even when nothing is actually captured. A generic lambda, such as [](auto x) { return x; }, receives no target signature from unary +. Instead, you can use int (*fp)(int) = [](auto x) { return x; };. An overloaded operator+ for a class type can have different semantics.

The example targets compilation in C++23 mode. The sources show the evolving standard draft, not a frozen C++23 edition. Expected output does not mean the code has been run here or that a production runtime has been attested.

Examples

#include <iostream>
#include <type_traits>

int main() {
    bool flag = true;
    auto number = +flag;
    static_assert(std::is_same_v<decltype(number), int>);

    auto twice = [](int x) { return x * 2; };
    auto fp = +twice;
    static_assert(std::is_same_v<decltype(fp), int (*)(int)>);

    std::cout << number << '\n' << fp(21) << '\n';
}

Result

1
42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources