Difference between revisions of "cpp/utility/declval"
From cppreference.com
(Undo revision 138822 by 69.174.157.229 (talk)) |
(Undo revision 138823 by 183.213.76.72 (talk)) |
||
Line 20: | Line 20: | ||
===Return value=== | ===Return value=== | ||
Cannot be called and thus never returns a value. The return type is {{tt|T&&}} unless {{tt|T}} is (possibly cv-qualified) {{tt|void}}, in which case the return type is {{tt|T}}.<!--Note that reference collapsing may take place when determine what T&& refers to.--> | Cannot be called and thus never returns a value. The return type is {{tt|T&&}} unless {{tt|T}} is (possibly cv-qualified) {{tt|void}}, in which case the return type is {{tt|T}}.<!--Note that reference collapsing may take place when determine what T&& refers to.--> | ||
+ | |||
+ | ===Possible implementation=== | ||
+ | {{eq fun | ||
+ | | 1= | ||
+ | template<typename T> auto declval() -> T; | ||
+ | }} | ||
===Example=== | ===Example=== |
Revision as of 17:29, 17 March 2022
Defined in header <utility>
|
||
template<class T> typename std::add_rvalue_reference<T>::type declval() noexcept; |
(since C++11) | |
Converts any type T
to a reference type, making it possible to use member functions in decltype expressions without the need to go through constructors.
declval
is commonly used in templates where acceptable template parameters may have no constructor in common, but have the same member function whose return type is needed.
Note that declval
can only be used in unevaluated contexts and is not required to be defined; it is an error to evaluate an expression that contains this function. Formally, the program is ill-formed if this function is odr-used.
Contents |
Parameters
(none)
Return value
Cannot be called and thus never returns a value. The return type is T&&
unless T
is (possibly cv-qualified) void
, in which case the return type is T
.
Possible implementation
template<typename T> auto declval() -> T; |
Example
Run this code
#include <utility> #include <iostream> struct Default { int foo() const { return 1; } }; struct NonDefault { NonDefault() = delete; int foo() const { return 1; } }; int main() { decltype(Default().foo()) n1 = 1; // type of n1 is int // decltype(NonDefault().foo()) n2 = n1; // error: no default constructor decltype(std::declval<NonDefault>().foo()) n2 = n1; // type of n2 is int std::cout << "n1 = " << n1 << '\n' << "n2 = " << n2 << '\n'; }
Output:
n1 = 1 n2 = 1
See also
decltype specifier(C++11)
|
obtains the type of an expression or an entity |
(C++11)(removed in C++20)(C++17) |
deduces the result type of invoking a callable object with a set of arguments (class template) |