zoukankan      html  css  js  c++  java
  • c++类型形参的实参的受限转换

    缘起:《c++ primer》 4th, 528页,习题16.3

    源程序

    #include <iostream>
    #include <vector>
    #include <list>
    using namespace std;
    
    template<class S>
    int compare(const S &v1, const S &v2)
    {
        if (v1 < v2)
            return -1;
        else if(v1 > v2)
            return 1;
        else
            return 0;
    }
    
    int main()
    {
        string s1 = "hi";
        string s2 = "world"; 
        cout << "string:" << compare(s1, s2) << endl;
        cout << "hi:" << compare("hi", "world") << endl; }

    错误提示

    函数模板中定义的类型S,在函数的两个参数中,类型必须相同,但是编译错误,提示:一个类型为char[3],另一个类型为char[6].这就引出一条实参的受限转换。

    数组或函数到指针的转换:如果模板形参不是引用类型,则对数组或函数类型的实参应该用常规指针转换。数组实参将当做指向第一个元素的指针,函数实参当做指向函数类型的指针。

    下边程序就可以了

    #include <iostream>
    #include <vector>
    using namespace std;
    
    template<class S>
    int compare(const S v1, const S v2)
    {
        if (v1 < v2)
            return -1;
        else if(v1 > v2)
            return 1;
        else
            return 0;
    }
    
    int main()
    {
        char a[] = "abcd";
        char b[] = "12345";
        cout << compare(a, b) << endl;
    }


    注意直接传字串默认是const类型, 比如

    #include <iostream>
    #include <vector>
    using namespace std;
    
    template<class S>
    int compare(const S v1, const S v2)
    {
        if (v1 < v2)
            return -1;
        else if(v1 > v2)
            return 1;
        else
            return 0;
    }
    
    int main()
    {
        char a[] = "abcd";
        char b[] = "12345";
        cout << compare(a, "1234") << endl;
    }

    错误提示:

    改成正确的:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    template<class S>
    int compare(const S v1, const S v2)
    {
        if (v1 < v2)
            return -1;
        else if(v1 > v2)
            return 1;
        else
            return 0;
    }
    
    int main()
    {
        const char a[] = "abcd";
        char b[] = "12345";
        cout << compare(a, "1234") << endl;
    }
  • 相关阅读:
    快速搭建 STF开源云测平台 测试人员专用
    快速搭建sonarqube代码检测平台
    使用jenkins交付微服务应用至kubernetes集群
    普通主机拥有集群控制权限
    为ingress资源添加basic auth认证
    GO语言入门
    GO语言入门
    GO语言入门
    GO语言入门
    关闭提示的下拉框
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3338496.html
Copyright © 2011-2022 走看看