问题描述
限时送ChatGPT账号..template<typename T>
struct foo{
void f(){
decltype(*this) a(*this);
do_some_test(a);
}
T data;
};
//compiler won't accept this
在我的解释中,decltype
应该返回 a 类型,以便我们可以在声明中使用它.但是google说在decltype(x)
中,如果x
是一个左值,它会返回T&
where T
> 是 x 的类型.
In my interpretation, decltype
should return the a type so that we can use it in declaration. But google says that in decltype(x)
,if x
is a lvalue, it will return T&
where T
is the type of x.
但是他们设计它来返回引用的目的是什么?此外,我应该怎么做才能在模板中创建与 *this
具有相同类型的类的实例?
But what they designed it to return a reference for? Furthermore, what should I do to create a instance of the class that has the same type as *this
in a template?
推荐答案
decltype
推导出 表达式 的类型,除非它应用于变量,在这种情况下它推导出该变量的类型:
decltype
deduces the type of expression, unless it is applied to a variable, in which case it deduces the type of that variable:
decltype(e)
表示的类型定义如下:
——如果 e 是一个无括号的 id 表达式或一个无括号的类成员访问,decltype(e)
是由 e
命名的实体的类型.如果没有这样的实体,或者如果 e
命名了一组重载函数,则程序格式错误;
— if e is an unparenthesized id-expression or an unparenthesized class member access, decltype(e)
is the type of the entity named by e
. If there is no such entity, or if e
names a set of overloaded functions, the program is ill-formed;
——否则,如果 e
是 xvalue,decltype(e)
是 T&&
,其中 T
是 e
的类型;
— otherwise, if e
is an xvalue, decltype(e)
is T&&
, where T
is the type of e
;
——否则,如果 e
是左值,decltype(e)
是 T&
,其中 T
是e
的类型;
— otherwise, if e
is an lvalue, decltype(e)
is T&
, where T
is the type of e
;
——否则,decltype(e)
是e
的类型.
§7.1.6.2 [dcl.type.simple]
§7.1.6.2 [dcl.type.simple]
取消引用一个指针会产生一个左值,因此 decltype
会推导出一个对被指点类型的左值引用:
Dereferencing a pointer yields an lvalue, and therefore decltype
will deduce an lvalue reference to the type of the pointee:
一元 *
运算符执行间接操作:应用它的表达式应该是指向对象类型的指针或指向函数类型的指针,结果是引用该对象的左值或表达式指向的函数.
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]
§5.3.1 [expr.unary.op]
因此decltype(*p)
,对于某个指针p
,会推导出对被指针类型的左值引用.
Therefore decltype(*p)
, for some pointer p
, deduces an lvalue reference to the type of the pointee.
如果你想从某个指针p
中得到指针的类型,你可以使用:
If you wish to get the type of the pointee from some pointer p
, you can use:
std::remove_pointer<decltype(p)>::type
或者:
std::remove_reference<decltype(*p)>::type
或者,在您的示例中,您可以简单地说 foo
,不需要类型推导.
Or, in your example, you can simply say foo
, type deduction is not required.
这篇关于C++:为什么 decltype (*this) 返回引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论