前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >深入理解C++11_c++ string char

深入理解C++11_c++ string char

作者头像
全栈程序员站长
发布2022-09-30 10:04:16
2760
发布2022-09-30 10:04:16
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

1. 语法

代码语言:javascript
复制
decltype ( expression )

decltype(declare type)用于查询表达式的类型,即编译时期进行自动类型推导。如上所示,该语句返回expression表达式的类型。

注意:decltype仅仅是查询表达式的类型,并不会对表达式求值。

2. 推导规则

1)如果 expression是一个不被括号( )包围的表达式,或者是一个类成员访问表达式,或者是一个单独的变量,那么 decltype(exp) 的类型就和 exp 一致,这是最普遍最常见的情况。

2)如果 expression是函数调用,那么 decltype(exp) 的类型就和函数返回值的类型一致。

3)如果 expression是一个左值,或者被括号( )包围,那么 decltype(expression) 的类型就是 expression的引用;假设 expression的类型为 T,那么 decltype(expression) 的类型就是 T&。

3. auto与decltype

代码语言:javascript
复制
auto varname = value;
decltype(exp) varname = value;

1)auto 根据=右边的初始值 value 推导出变量的类型,而 decltype 根据 exp 表达式推导出变量的类型,跟=右边的 value 没有关系;

2)auto 要求变量必须初始化,而 decltype 不要求,即可以写成这样“decltype(exp) varname;”;

4. 基本使用

代码语言:javascript
复制
const int&& foo();
int i;
struct A { double x; };
const A* a = new A();

decltype(foo())  x1 = 1;  // const int&&      (1)
decltype(i)      x2;      // int              (2)
decltype(a->x)   x3;      // double           (3)
decltype((a->x)) x4 = 1;  // double&          (4)

5. 实例

代码语言:javascript
复制
#include <iostream>
#include <type_traits>
using namespace std;

struct A { double x; };
const A* a;

decltype(a->x) y;       // type of y is double (declared type)
decltype((a->x)) z = y; // type of z is const double& (lvalue expression)

template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) // return type depends on template parameters
									  // return type can be deduced since C++14
{
	return t + u;
}

int main()
{
	int i = 33;
	decltype(i) j = i * 2;

	std::cout << "i and j are the same type? " << std::boolalpha
		<< std::is_same_v<decltype(i), decltype(j)> << '\n';

	std::cout << "i = " << i << ", "
		<< "j = " << j << '\n';

	auto f = [](int a, int b) -> int
	{
		return a * b;
	};

	decltype(f) g = f; // the type of a lambda function is unique and unnamed
	i = f(2, 2);
	j = g(3, 3);

	std::cout << "i = " << i << ", "
		<< "j = " << j << '\n';

	system("pause");
	return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年9月9日 下,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 语法
  • 2. 推导规则
  • 3. auto与decltype
  • 4. 基本使用
  • 5. 实例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档