template<typename T>
struct foo{
void f(){
decltype(*this) a(*this);
do_some_test(a);
}
T data;
};
//compiler won't accept this
在我的解释中,decltype
应该返回 a 类型,以便我们可以在声明中使用它。但是谷歌说在 decltype(x)
中,如果 x
是左值,它将返回 T&
where T
是 x 的类型。
但是他们将其设计为返回引用的目的是什么?此外,我应该如何创建与模板中的 *this
具有相同类型的类的实例?
最佳答案
decltype
推导表达式 的类型,除非它应用于变量,在这种情况下它推导该变量的类型:
The type denoted by
decltype(e)
is defined as follows:— if e is an unparenthesized id-expression or an unparenthesized class member access,
decltype(e)
is the type of the entity named bye
. If there is no such entity, or ife
names a set of overloaded functions, the program is ill-formed;— otherwise, if
e
is an xvalue,decltype(e)
isT&&
, whereT
is the type ofe
;— otherwise, if
e
is an lvalue,decltype(e)
isT&
, whereT
is the type ofe
;— otherwise,
decltype(e)
is the type ofe
.§7.1.6.2 [dcl.type.simple]
取消引用一个指针会产生一个左值,因此 decltype
将推导出一个对指针对象类型的左值引用:
The unary
*
operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.§5.3.1 [expr.unary.op]
因此,对于某些指针 p
,decltype(*p)
推导出指向对象类型的左值引用。
如果你想从一些指针 p
得到指针对象的类型,你可以使用:
std::remove_pointer<decltype(p)>::type
或者:
std::remove_reference<decltype(*p)>::type
或者,在您的示例中,您可以简单地说foo
,不需要类型推导。
关于C++:为什么 decltype (*this) 返回一个引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25312225/