面试之快速学习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;
相关推荐
云和数据.ChenGuang7 小时前
Python 常见特殊方法详解:__new__、__init__、__del__、__str__、__repr__ 与 __getattribute__
开发语言·人工智能·python·1024程序员节
xyouyuweizhu7 小时前
字节流与字符流:Java IO 的两条主线该怎么选
java·开发语言·python
m4Rk_7 小时前
【论文阅读】Agent 记忆机制(113):Agentic Memory Management——从“检索相关信息”走向“管理 Agent 内部记忆”
论文阅读·人工智能·学习·开源·github
小超人诞生日记8 小时前
C++ 异常机制详解:从抛出捕获到异常安全
c++·算法
多弗朗皮卡丘8 小时前
C++的IO流
开发语言·c++·io流·文件io流
骑着蜗牛撵大象3278 小时前
AI Agent 工程化开发实战(三):用 StateGraph 给智能体搭一条可回放的状态流水线
java·开发语言·jvm·ai·状态管理·langgraph·stategraph
辣知8 小时前
辣知·化智92 《山海经》里的史前密码
学习
itmigrate8 小时前
Rust 里的所有权误区:不是不写 clone 就叫高性能
开发语言·后端·rust
Brilliantwxx8 小时前
【Linux】 文件访问与路径解析:目录、文件名、dentry、路径缓冲与 dcache 全解析
linux·运维·服务器·开发语言·spring
鬼手点金9 小时前
KV Cache 未必是一次性的:可编辑、可组合的“笔记”
java·人工智能·笔记·学习·自动化·1024程序员节