栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++(14):函数返回类型自动推导

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++(14):函数返回类型自动推导

C++11可以通过结合auto和decltype来动态的声明函数的返回值类型:

#include 
using namespace std;

template
auto add(T1 t1, T2 t2) -> decltype(t1 + t2)
{
	return t1 + t2;
}

int main(){
	auto a = add(5, 1.66);
	cout<<"a="<

C++14可以通过更为简化的方式,只通过auto来动态的声明函数的返回值类型:

#include 
using namespace std;

template
auto add(T1 t1, T2 t2)
{
	return t1 + t2;
}

int main(){
	auto a = add(5, 1.66);
	cout<<"a="<

对于大部分情况,通过auto都可以准确的推导出返回值类型,不过当需要返回引用时,auto就力不从心了:

auto g(vector& data, int index)
{
	return data[index];
}

vector d = {1, 2, 3, 4};
g(d, 0) = 0;    //由于auto被推到出是个值类型的int,因此是个右值,无法编译

这种情况,可以通过decltype(auto)来对返回值类型进行推导,auto相当于占位符,decltype会根据返回值的具体类型推导出函数的返回值类型:

#include 
#include 
#include 
using namespace std;


decltype(auto) g(vector& data, int index)   
{
	return data[index];
}

int main()
{
	vector d = {1, 2, 3, 4};
	g(d, 0) = 0;    //由于函数g的返回值被推导为int&, 因此可以对返回的引用进行赋值
	for(auto i : d)
	{
		cout< 

decltype(auto)这种形式,不仅仅可以用于声明函数的返回值,也可以用于声明变量:

#include 
using namespace std;

int main()
{
	int const x = 1;
	auto a = x;
	cout<::value<::value< 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/892687.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号