为什么std :: declval添加一个引用? [英] Why does std::declval add a reference?

查看:313
本文介绍了为什么std :: declval添加一个引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: declval 是编译时实用程序用于构造表达式以确定其类型。它定义如下:

std::declval is a compile-time utility used to construct an expression for the purpose of determining its type. It is defined like this:

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

这不是更简单吗?

template< class T >
T declval() noexcept;

引用返回类型的优点是什么?不应该叫 declref

What is the advantage of a reference return type? And shouldn't it be called declref?

我发现的最早的历史例子是 n2958 ,它调用函数 value()但总是返回一个引用。

The earliest historical example I find is n2958, which calls the function value() but already always returns a reference.

注意, decltype 的操作数不需要具有可访问的析构函数,即它不作为完全表达式语义地检查。

Note, the operand of decltype does not need to have an accessible destructor, i.e. it is not semantically checked as a full-expression.

template< typename t >
t declprval() noexcept;

class c { ~ c (); };
decltype ( declprval< c >() ) * p = nullptr; // OK


推荐答案

decltype 中返回对象类型的prvalue仅适用于函数调用本身是 decltype 的操作数或一个逗号运算符的右操作数,它是 decltype (§5.2.2[expr.call] / p11)的操作数,这意味着 declprval 在OP中,

The "no temporary is introduced for function returning prvalue of object type in decltype" rule applies only if the function call itself is either the operand of decltype or the right operand of a comma operator that's the operand of decltype (§5.2.2 [expr.call]/p11), which means that given declprval in the OP,

template< typename t >
t declprval() noexcept;

class c { ~ c (); };

int f(c &&);

decltype(f(declprval<c>())) i;  // error: inaccessible destructor

更一般来说,返回 T 会阻止对不完整类型使用 declval 的大多数非平凡用法,使用私有析构函数类型,类似:

doesn't compile. More generally, returning T would prevent most non-trivial uses of declval with incomplete types, type with private destructors, and the like:

class D;

int f(D &&);

decltype(f(declprval<D>())) i2;  // doesn't compile. D must be a complete type

这样做没有什么好处,因为xvalues几乎与prvalues不可区分,除非当你在它们上使用 decltype 时,通常不会直接使用 decltype $ c> declval - 你已经知道类型了。

and doing so has little benefit since xvalues are pretty much indistinguishable from prvalues except when you use decltype on them, and you don't usually use decltype directly on the return value of declval - you know the type already.

这篇关于为什么std :: declval添加一个引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆