Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::plus — addition function object

std::plus from <functional> exposes operator + as a callable object. std::plus<T> fixes the type T, whereas std::plus<> deduces the argument types and the expression's result type.

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

Syntax

#include <functional>
std::plus<T>{}(x, y)
std::plus<>{}(x, y)

std::plus is a class template declared in <functional>. The expression std::plus<int>{}(2, 3) constructs an object and calls its operator(). Such an object can be passed to an algorithm as a binary operation.

std::plus<T> takes two arguments through const T& and returns T, computing x + y. Conversions to T can therefore occur before addition.

std::plus<>, meaning std::plus<void>, deduces both types separately and forwards arguments while preserving their value categories. Its result type is determined by decltype(std::forward<T>(t) + std::forward<U>(u)). It also exposes the type marker is_transparent.

Both forms require a valid + expression; they add no safety checks of their own. Their operator() is constexpr, so suitable arguments allow the result to be computed at compile time.

Examples

#include <functional>
#include <iostream>
#include <type_traits>

int main() {
    constexpr auto typed = std::plus<int>{}(2, 3);
    constexpr auto mixed = std::plus<>{}(2, 3.5);

    static_assert(typed == 5);
    static_assert(mixed == 5.5);
    static_assert(std::is_same_v<decltype(std::plus<>{}(2, 3.5)), double>);

    std::cout << typed << '\n' << mixed << '\n';
}

Result

5
5.5

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