c++ 11 新特性(未完待续)

150 阅读2分钟
  1. 字符串原始字面量

    在c++中,当字符串中包含反斜杠时,表示进行转义。若转义字符有明确含义,那么在输出时则会转化成对应的表示,反斜杠并不会输出;若没有对应的表示,则既不输出反斜杠,也不输出对应的表示,反斜杠后面的字母原样输出。如果要想输出原始字符串,可以在反斜杠前面再加一个反斜杠,如下:

    string str = "\hello \world \ted"; // 输出为 hello world     ed
    string str = "\\hello \\world \\ted"; // 输出为 \hello \world \ted
    

    c++11提供了原始字面量方法,可以实现输出原始字符串。如下:

    // 格式  R"xxx()xxx"  其中R和括号是必须的,括号外面的xxx可以看作注释,并不会输出,但是括号前后的xxx要相同
    string str = R"(\hello \world \ted)"; // 输出为 \hello \world \ted
    string str = R"test(\hello \world \ted)test"; // 输出为 \hello \world \ted
    
  2. 指针空值类型nullptr

  3. auto使用场景

    1. STL遍历

      map<int, string> mp;
      mp.insert(make_pair(1, "a"));
      mp.insert(make_pair(2, "b"));
      map<int, string>::iterator it = mp.begin();
      for (; it != mp.end(); it++) {
      	cout << "Key: " << it->first << ", Value: " << it->second << endl;
      }
      cout << "--------------------------" << endl;
      auto it1 = mp.begin();
      for (; it1 != mp.end(); it1++) {
      	cout << "Key: " << it1->first << ", Value: " << it1->second << endl;
      }
      
      // output
      //Key: 1, Value: a
      //Key: 2, Value: b
      //--------------------------
      //Key: 1, Value: a
      //Key: 2, Value: b
      
    2. 模板函数场景自动类型推导

      class T1 {
      public:
          static string get() {
              return "T1";
          }
      };
      
      class T2 {
      public:
          static int get() {
              return 2;
          }
      };
      
      // ------方法一------
      template<class T>
      void func() {
          auto ret = T::get();  // 返回值类型可以是string / int
          cout << ret << endl;
      }
      
      func<T1>();
      func<T2>();
      
      
      // ------方法二------
      template<class T, typename P>
      void func1() {
          P ret = T::get();
          cout << ret << endl;
      }
      
      func1<T1, string>();
      func1<T2, int>();
      
  4. decltype

    在编译时,decltype可以分析出表达式的数据类型,而不用执行表达式

    decltype(exp)
    // 规则如下:
    // 1. 当exp是不加括号的表达式、类访问表达式、普通变量时,decltype(exp)类型与exp一致
    // 2. 当exp是函数调用时,decltype(exp)类型与函数返回值类型一致
    // 3. 当exp是左值 或者 被括号包围时,decltype(exp)类型是exp的引用
    
  5. 返回类型后置

    // 注意事项
    // 1. 不可以只使用auto, 因为 auto 必须结合初始化, 此处可以追踪decltype推导出来的类型
    // 2. 不能直接把decltype(t + u) 放在前面,因为 t 和 u 的作用域不包括前面
    template<typename T, typename U>
    auto add(T t, U u) -> decltype(t + u) {
    	return t + u;
    }