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

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

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

eg:

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 结合起来完成返回值类型的推导
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 重定义类型是很方便的,但它也有一些限制,比如,无法重定义一个模板
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 却很难办到。
 template <typename T>
 typedef std::map<std::string, T>map_T_t;  //报错A typedef cannot be a template
  1. 修改一下是可以的
template <typename Val>
struct str_map
{
    typedef std::map<std::string, Val> type;
};
str_map<int>::type map1;
  1. 现在,在 C++11 中终于出现了可以重定义一个模板的语法。请看下面的示例:
template <typename Val>
using str_map_t = std::map<int, Val>;
str_map_t<int> map2;
  1. using 的别名语法覆盖了 typedef 的全部功能
// 重定义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. 方法定义
typedef void(*fun_t1)(int, int);
using fun_t2 = void(*)(int , int);
/*
  1. 进阶模版
/* 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;

你可能感兴趣的:(面试之快速学习c++11,学习,c++,开发语言)