首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::declval

Defined in header <utility>

template<class T> typename std::add_rvalue_reference<T>::type declval();

(since C++11)

转换任何类型T的引用类型,从而可以在decltype表达式,不需要遍历构造函数。

declval通常在模板中使用,其中可接受的模板参数可能没有共同的构造函数,但具有相同的成员函数,其返回类型是必需的。

请注意,因为没有定义declval,它只能用于未评估上下文;计算包含此函数的表达式是错误的。形式上,如果此函数是ODR-使用...

参数

%280%29

返回值

无法调用,因此永远不会返回值。返回类型是T&&除非T%28可能是cv-合格%29void,在这种情况下,返回类型是T...

例外

noexcept规格:

noexcept

二次

代码语言:javascript
复制
#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;                   // 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';
}

二次

产出:

二次

代码语言:javascript
复制
n1 = 1
n2 = 1

二次

另见

decltype specifier

defines a type equivalent to the type of an expression (C++11)

result_ofinvoke_result (C++11)(deprecated in C++17)(C++17)

deduces the result type of invoking a callable object with a set of arguments (class template)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券