C++:为什么 decltype (*this) 返回一个引用?

标签 c++ templates generic-programming

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 by e. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;

— otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;

— otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;

— otherwise, decltype(e) is the type of e.

§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]

因此,对于某些指针 pdecltype(*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/

相关文章:

c++ - GCC - 包含编译标志的宏

c++ - Visual Studio 2010 无法打开 VC++ 包含文件

string - Go 中的模板字符串?

asp.net-mvc - ASP.NET MVC 3 中的条件布局

java - java中泛型类中的double方法

c# - 很好的泛型介绍

c++ - QT连接没有匹配的函数可以调用

c++ - time(*time_t) 获取不到当前时间(作业)

c++ - 模板类方法语法

racket - 打字 Racket : Creating generic types with define-type