面试之快速学习c++11 - C++返回值类型后置(跟踪返回值类型) 和 using

学习地址: http://c.biancheng.net/view/3730.html

1. C++返回值类型后置(跟踪返回值类型)

eg:

c 复制代码
template <typename R, typename T, typename U>
R add1(T t, U u)
{
    return t+u;
}

void testAdd1() {
    int a = 1;
    float b = 1.0;
    auto result = add1<decltype(a+b)>(a, b);
}
  1. 上面的表达式看着是没问题的, decltype(a+b)可以推导出来返回值,但是有问题外部人员怎么会知道里面做的是a+b ?
  2. 返回类型后置(trailing-return-type,又称跟踪返回类型)语法,将 decltype 和 auto 结合起来完成返回值类型的推导
c 复制代码
template <typename  T, typename U>
auto add2(T t, U u) -> decltype(t+u) {
    return t+u;
}

int& foo2(int& i);
float foo2(float& f);

template <typename T>
auto func2(T& val) -> decltype(foo(val))
{
    return foo(val);
}

2. using

  1. 在 C++ 中可以通过 typedef 重定义一个类型 typedef unsigned int uint_t;
  2. 使用 typedef 重定义类型是很方便的,但它也有一些限制,比如,无法重定义一个模板
c 复制代码
typedef std::map<std::string, int>map_int_t;
typedef std::map<std::string, std::string>map_string_t;
  1. 我们需要的其实是一个固定以 std::string 为 key 的 map,它可以映射到 int 或另一个 std::string。然而这个简单的需求仅通过 typedef 却很难办到。
c 复制代码
 template <typename T>
 typedef std::map<std::string, T>map_T_t;  //报错A typedef cannot be a template
  1. 修改一下是可以的
c 复制代码
template <typename Val>
struct str_map
{
    typedef std::map<std::string, Val> type;
};
str_map<int>::type map1;
  1. 现在,在 C++11 中终于出现了可以重定义一个模板的语法。请看下面的示例:
c 复制代码
template <typename Val>
using str_map_t = std::map<int, Val>;
str_map_t<int> map2;
  1. using 的别名语法覆盖了 typedef 的全部功能
c 复制代码
// 重定义unsigned int
typedef unsigned int uint_t;
using uint_t = unsigned int;
// 重定义std::map
typedef std::map<std::string, int> map_int_t;
using map_int_t = std::map<std::string, int>;
  1. 方法定义
c 复制代码
typedef void(*fun_t1)(int, int);
using fun_t2 = void(*)(int , int);
/*
  1. 进阶模版
c 复制代码
/* C++98/03 */
template <typename T>
struct func_t
{
   typedef void (*type)(T, T);
};
// 使用 func_t 模板
func_t<int>::type xx_1;
/* C++11 */
template <typename T>
using func_t3 = void (*)(T, T);
// 使用 func_t 模板
func_t3<int> xx_2;
相关推荐
为何创造硅基生物3 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
吃好睡好便好3 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
星寂樱易李4 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
仰泳之鹅4 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
nashane4 小时前
HarmonyOS 6学习:CapsLock键失效诊断与长截图完整实现指南
学习·华为·harmonyos
之歆4 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
于小猿Sup5 小时前
VMware在Ubuntu22.04驱动Livox Mid360s
linux·c++·嵌入式硬件·自动驾驶
cen__y5 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git
AI人工智能+电脑小能手5 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
xian_wwq6 小时前
【学习笔记】AGC协调控制系统概述
笔记·学习