template<typename T>
struct foo{
void f(){
decltype(*this) a(*this);
do_some_test(a);
}
T data;
};
//compiler won't accept this
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.
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 deduces the type of expression, unless it is applied to a variable, in which case it deduces the type of that variable:
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 ifenames a set of overloaded functions, the program is ill-formed;— otherwise, if
eis an xvalue,decltype(e)isT&&, whereTis the type ofe;— otherwise, if
eis an lvalue,decltype(e)isT&, whereTis the type ofe;— otherwise,
decltype(e)is the type ofe.§7.1.6.2 [dcl.type.simple]
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]
Therefore decltype(*p), for some pointer p, deduces an lvalue reference to the type of the pointee.
If you wish to get the type of the pointee from some pointer p, you can use:
std::remove_pointer<decltype(p)>::type
Or:
std::remove_reference<decltype(*p)>::type
Or, in your example, you can simply say foo, type deduction is not required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With