zoukankan      html  css  js  c++  java
  • C++ template学习总结6

    对于基本类型来说,并没有一个default模式来讲他们初始化为有意义的值,没有初始化的变量,其指都是未定义的,但是在模板这一块呢?我们可以采用下面的形式:

    template <typename T> 
    void foo() 
    { 
        T x = T();    // x is zero (or false)ifT is a built-in type 
    } 
    

    对于class template我们可以采用下面例子的方式:

    template <typename T> 
    class MyClass { 
      private: 
        T x; 
      public: 
        MyClass() : x() {  // ensures that x is initialized even for built-in types 
        } 
        … 
    }; 
    

    通过引用形式将字串字面常数传递给模板,有时候会遇到错误:

    #include <string> 
    
    // note: reference parameters 
    template <typename T> 
    inline T const& max (T const& a, T const& b) 
    { 
        return a < b ? b : a; 
    } 
    
    int main() 
    { 
        std::string s; 
    
        ::max("apple","peach");   // OK: same type 
        ::max("apple","tomato");  // ERROR: different types 
        ::max("apple",s);         // ERROR: different types 
    } 

    问题出在于这几个字串字面常数的长度不同,因此其底层的Array也是不同的。换句话说“apple”

    是char const[6],”tomato“是char const[7].

    但是如果你使用传值形式的话,那么久是可以的。

    #include <string> 
    
    // note: nonreference parameters 
    template <typename T> 
    inline T max (T a, T b) 
    { 
        return a < b ? b : a; 
    } 
    int main() 
    { 
        std::string s; 
    
        ::max("apple","peach");   // OK: same type 
        ::max("apple","tomato");  // OK: decays to same type 
        ::max("apple",s);         // ERROR: different types 
    } 

    这种方式之所以可以,是因为在引数的推倒过程中,只有当参数不是一个引用的时候,【array转换为pointer】的动作才会发生,这个规则我们用下面的例子来说明:

    #include <typeinfo> 
    #include <iostream> 
    
    template <typename T> 
    void ref (T const& x) 
    { 
        std::cout << "x in ref(T const&): " 
                  << typeid(x).name() << '\n'; 
    } 
    
    template <typename T> 
    void nonref (T x) 
    { 
        std::cout << "x in nonref(T): " 
                  << typeid(x).name() << '\n'; 
    } 
    
    int main() 
    { 
        ref("hello"); 
        nonref("hello"); 
    } 

    结果为:image

    其实在这个例子中,最好的方式是对string进行重载,这么做尤其必要的,如果不这么做的弧啊,对于两个字串字面常熟调用max()是合法的,但是max()会以operator<比较两个指针的大小,所比较的其实是两个指针的地址,而不是其字面值,这也就是为什么使用std::string比C-style字串要好的原因之一。

    image

    只有当你以by value的方式使用字串字面常熟的时候,字串底部的array才会被转型(退化)为一个字元指针。也就是array to pointer。

  • 相关阅读:
    mui 时间选择器和上传图片
    css实现聊天气泡效果
    css总结 -使用display:inline-block,出现元素高度错位
    js DIV延时几秒后消失或显示代码
    js监听textarea 内容的变化,并计算内容的长度c
    生成git的SSH公钥
    IDEA中把普通的Java项目转换成gradle项目
    Idea中自动生成get,set,toString等方法
    IDEA中阿里P3C插件的安装与使用
    IDEA中SonarLint的安装与使用
  • 原文地址:https://www.cnblogs.com/rollenholt/p/2384977.html
Copyright © 2011-2022 走看看