面试之快速学习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;
相关推荐
虚假程序设计9 分钟前
pythonnet python图像 C# .NET图像 互转
开发语言·人工智能·python·opencv·c#·.net
归寻太乙15 分钟前
C++函数重载完成日期类相关计算
开发语言·c++
尽蝶叙17 分钟前
C++:分苹果【排列组合】
开发语言·c++·算法
憧憬成为原神糕手42 分钟前
c++_list
开发语言·c++
zyh2005043044 分钟前
c++的decltype关键字
c++·decltype
idealzouhu1 小时前
Java 并发编程 —— AQS 抽象队列同步器
java·开发语言
爱吃油淋鸡的莫何1 小时前
Conda新建python虚拟环境问题
开发语言·python·conda
闲人编程1 小时前
Python实现日志采集功能
开发语言·python·fluentd·filebeat·日志采集
Sol-itude1 小时前
关于MATLAB计算3维图的向量夹角总是不正确的问题记录
开发语言·matlab·问题解决·向量
2401_862886781 小时前
蓝禾,汤臣倍健,三七互娱,得物,顺丰,快手,游卡,oppo,康冠科技,途游游戏,埃科光电25秋招内推
前端·c++·python·算法·游戏