auto 和 decltype(auto) 类型推导示例
auto and delctype(auto) type deduction example
我读了一篇关于 auto
使用 decltype
进行类型推导的文章,我想知道我在下面的示例中关于如何推导类型的逻辑是否正确(所以如果我弄错了请纠正我:)
#include <iostream>
using namespace std;
class Widget
{
public:
Widget() = default;
};
int main()
{
Widget w;
const Widget& cw = w; // cw is const Widget&
auto myWidget1 = cw; // (1) myWidget1 is Widget
decltype(auto) myWidget2 = cw; // (2) myWidget2 is const Widget&
}
到目前为止我的理解是:
for 1 :使用自动类型推导,在这种情况下,它类似于按值传递的参数的模板类型推导。这意味着 cv-qualifiers 和 refs 被忽略,最终将导致 Widget
作为类型。
for 2: decltype 被使用然后传递给 auto 实际上是 cw
一个 const Widget& 然后所有都被设置并且类型是 const Widget&。
所以我wrote/understood是对还是错?
谢谢
这里有一个技巧,可以让编译器打印一个类型:
template <typename>
struct TD;
然后使用:
TD<decltype(myWidget1)>();
由于 TD<...>
是一个不完整的类型,编译器会报错,并会在错误消息中打印您的类型:
error: invalid use of incomplete type struct TD<Widget>
所以myWidget1
的类型是Widget
.
myWidget2
的类型:
error: invalid use of incomplete type struct TD<const Widget&>
所以它的类型确实是 const Widget &
,正如你所怀疑的那样。
所以是的,你所描述的是正确的。
我读了一篇关于 auto
使用 decltype
进行类型推导的文章,我想知道我在下面的示例中关于如何推导类型的逻辑是否正确(所以如果我弄错了请纠正我:)
#include <iostream>
using namespace std;
class Widget
{
public:
Widget() = default;
};
int main()
{
Widget w;
const Widget& cw = w; // cw is const Widget&
auto myWidget1 = cw; // (1) myWidget1 is Widget
decltype(auto) myWidget2 = cw; // (2) myWidget2 is const Widget&
}
到目前为止我的理解是:
for 1 :使用自动类型推导,在这种情况下,它类似于按值传递的参数的模板类型推导。这意味着 cv-qualifiers 和 refs 被忽略,最终将导致 Widget
作为类型。
for 2: decltype 被使用然后传递给 auto 实际上是 cw
一个 const Widget& 然后所有都被设置并且类型是 const Widget&。
所以我wrote/understood是对还是错?
谢谢
这里有一个技巧,可以让编译器打印一个类型:
template <typename>
struct TD;
然后使用:
TD<decltype(myWidget1)>();
由于 TD<...>
是一个不完整的类型,编译器会报错,并会在错误消息中打印您的类型:
error: invalid use of incomplete type
struct TD<Widget>
所以myWidget1
的类型是Widget
.
myWidget2
的类型:
error: invalid use of incomplete type
struct TD<const Widget&>
所以它的类型确实是 const Widget &
,正如你所怀疑的那样。
所以是的,你所描述的是正确的。