Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

The forwarding reference `F&&`

With `F` deduced, `F&&` can bind to either an lvalue or an rvalue. A direct call `f()` treats the callable as an lvalue; `std::forward<F>(f)` passes it on as an lvalue or rvalue according to the argument.

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

Syntax

#include <utility>

template<class F>
void call(F&& f) {
    std::forward<F>(f)();
}

In template<class F> void call(F&& f), the forwarding reference declarator (F&&) uses && directly with the type parameter F, without adding const or volatile, and F is deduced at the call. For an lvalue of type T, deduction gives F = T&, and reference collapsing makes f a T&. For an rvalue of type T, deduction gives F = T, so f is a T&&. Qualifiers on the argument type, such as const, are retained.

The spelling && is not enough. const F&&, a concrete type such as Callable&&, and F&& when F is already fixed by a class template specialization are not forwarding references.

In f(), the expression f is an lvalue even if the parameter's declared type is Callable&&. std::forward<F>(f) from <utility> uses the deduced F: for objects, it yields an lvalue for an lvalue argument and an xvalue (a kind of rvalue) for an rvalue argument. This can change which overload is selected: operator()() & or operator()() &&.

std::forward itself does not copy, move, or extend an object's lifetime. A temporary bound to a reference parameter lasts until the end of the full-expression containing the call. A reference retained to that temporary will dangle afterward.

Examples

#include <iostream>
#include <utility>

struct Callable {
    const char* operator()() & { return "lvalue"; }
    const char* operator()() && { return "rvalue"; }
};

template<class F>
void compare(F&& f) {
    const char* direct = f();
    const char* forwarded = std::forward<F>(f)();
    std::cout << direct << ' ' << forwarded << '\n';
}

int main() {
    Callable callable;
    compare(callable);
    compare(Callable{});
}

Result

lvalue lvalue
lvalue rvalue

Each line shows the result of `f()` first and `std::forward<F>(f)()` second. For `callable`, both calls select `&`; for `Callable{}`, the first selects `&` and the second selects `&&`. The example calls the object twice only to compare the overloads.

Related lessons

  • C++ · Lesson 24 · Advanced · Version: 3

Sources