std::declval

From Cppreference

Jump to: navigation, search
Defined in header <utility>

template< class T >
typename std::add_rvalue_reference<T>::type declval();
(C++11 feature)

Converts any type T to a reference type, making it possible to use member functions in decltype expressions without specifying constructors. It 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. std::declval can only be used in unevaluated contexts, it is an error to evaluate an expression that contains this function.

Contents

[edit] Parameters

(none)

[edit] Return value

Cannot be called, thus never returns a value, but the return type is T&& unless T is a reference type, in which case T& is returned.

[edit] Exceptions

noexcept specification:  
noexcept

  (C++11 feature)

[edit] 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; // will not compile
    decltype(std::declval<NonDefault>().foo()) n2 = n1; // int n2
    std::cout << "n2 = " << n2 << '\n';
}

Output:

n2 = 1

[edit] See also

decltype
(keyword)
result_of (C++11)
deduces the return type of a function call expresion
(class template)