std::declval

Defined in header <utility>
template< class T >
typename std::add_rvalue_reference<T>::type declval();
(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 because no definition exists for declval, it can only be used in unevaluated contexts; it is an error to evaluate an expression that contains this function. Formally, the program is ill-formed if this function is odr-used.

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.

Exceptions

noexcept specification:
noexcept

Example

#include <utility>
#include <iostream>
 
struct Default {
    int foo() const {return 1;}
};
 
struct NonDefault {
    NonDefault(const NonDefault&) {}
    int foo() const {return 1;}
};
 
int main()
{
    decltype(Default().foo()) n1 = 1; // int n1
//  decltype(NonDefault().foo()) n2 = n1; // error: no default constructor
    decltype(std::declval<NonDefault>().foo()) n2 = n1; // int n2
    std::cout << "n2 = " << n2 << '\n';
}

Output:

n2 = 1

See also

decltype specifier defines a type equivalent to the type of an expression (C++11)
(C++11)
deduces the return type of a function call expression
(class template)
doc_CPP
2016-10-11 10:02:16
Comments
Leave a Comment

Please login to continue.