关于尾置返回类型,auto和decltype

template<class T>
return_type func(T t)
{
    return *t;
}

此处的return_type该如何填写,可以通过decltype()来获得此类型。但是此时t还没有出现,编译器无法判断。

c++11提供了一种新的书写方式,将返回类型尾置。

template<class T>
auto func(T t)->decltype(*t)
{
    return *t;
}

 如果写成下面这样呢,把decltype去掉

template<class T>
auto func(T t)
{
    return *t;
}

这两者是不一样的

原因在与auto和decltype的区别,

在auto的自动推断类型中,会自动去掉&和顶层const,

在decltype的自动推断类型中,会保留原本的类型,并且如果表达式中有解引用,会自动转成引用,有双括号也会转成引用。

所以,前者的返回值可以作为左值,后者不行。

将后者改为下式,二者就一样了。

template<class T>
auto &func(T t)
{
    return *t;
}

在返回指向数组的指针中也可以使用

int (*)[5] func1(int temp[][5],int n)
{}
//可以写成下式
auto func1(int temp[][5],int n) -> int (*)[3]
{}

猜你喜欢

转载自blog.csdn.net/znzxc/article/details/81152970