Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::declval — inspect expressions without constructing an object

std::declval from <utility> lets you inspect an expression's type without constructing an object. Use it in unevaluated operands, such as decltype; it must not be used for an actual evaluated call.

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

Syntax

#include <utility>

template<class T>
std::add_rvalue_reference_t<T> std::declval() noexcept;

std::declval<T>() from <utility> builds expressions in unevaluated operands, such as decltype. It constructs no object, so you can inspect operations even when T has no accessible default constructor.

Its return type is std::add_rvalue_reference_t<T>. For an object type T, the expression is an xvalue of type T; for T&, it is an lvalue because of reference collapsing. Consequently, std::declval<T>() and std::declval<T&>() can select different overloads. For void, the result type is void, not the invalid void&&.

The function must not be odr-used: an actual evaluated call is forbidden, including during constant evaluation. The parameter T may be incomplete, but the inspected operation must still be valid; accessing members may require a complete definition.

The example distinguishes the &- and &&-qualified overloads of read(). The constructor Sensor() is deleted, and the read() functions are only declared: no object is constructed and no call is executed. Assertions check the types during compilation; the program prints nothing.

Examples

#include <type_traits>
#include <utility>

struct Sensor {
    Sensor() = delete;
    int read() &;
    double read() &&;
};

using LvalueResult = decltype(std::declval<Sensor&>().read());
using RvalueResult = decltype(std::declval<Sensor>().read());

static_assert(std::is_same_v<LvalueResult, int>);
static_assert(std::is_same_v<RvalueResult, double>);
static_assert(std::is_same_v<decltype(std::declval<void>()), void>);

int main() {}

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