×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / IT技术讨论 / C++中模板函数的重载
    在C++中,对模板函数有两种重载方法,一是利用函数模板的函数体;二是重新定义函数体。哪位C++高手能告诉下面一段程序在GNU下面的有什么问题(利用第一种方法重载模板函数)

    #include <iostream.h>

    template <class T>
    T max (T x, T y)
    {
    cout << "This is the template function! max is: ";
    return (x>y) ? x:y;
    }

    int max(int, int);
    char max(char, char);

    main()
    {
    int i = 10;
    char c = 'a';
    float f = 43.74;

    cout << max(i,i) << "\n";
    cout << max(c,c) << "\n";
    cout << max(i,c) << "\n";
    cout << max(c,i) << "\n";
    cout << max(f,f) << "\n";
    cout << max(f,i) << "\n";
    return 1;
    }
    • The program won't link because the two functions int max(int, int) and char max(char, char) are not defined.
      In order to tell compiler that you are using a templated function, you have put the angle bracket after the function name: cout<<max<int>(i,i)<<encl;
      • C++中模板函数的重载
        这是一个重载模板函数的问题,所以我们还是先从模板函数的特点入手来分析这个问题。

        模板函数的特点告诉我们,虽然模板参数 T 可以实例化成各种类型,但是采用模板参数 T 的各参数之间必须保持完全一致的类型。模板类型并不具有隐式的类型转换,例如int 与char 之间,float 与 int 之间,float 与 double 之间等。所以我们看下面的例子就知道有些语句是不能通过编译的。

        template < class T>
        T max (T x, T y) {
        return ( x > y) ? x: y;
        }

        void func(int i, char c, float f) {
        {
        max(i,i); // 正确
        max(c,c); // 正确
        max(i,c); // 错误
        max(c,i); // 错误
        max(f,f); // 正确
        max(i,f); // 错误
        max(f,i); // 错误
        }

        从上面的例子可以看出,当参数类型完全一致时语句才是正确的。

        由于类型转换在C++中是非常普遍的,解决这个问题的方法是允许函数模板参与重载。这便是我在上一个问题中所列举的两种重载方法。

        对于两位高手的见解我非常感谢。不过我个人认为tony的回答好像比较正确。我是在linux上用GNU的C++编译器,我再去试试,或许是
        int max(int, int) 和 char max(char, char)只需要申明一个就可以了。
    • What does GNU mean?…..
      In some compilers, they don’t need to be defined. But only one of them can be declared. You won’t pass compilation if you declare both int max(int, int); and char max(char, char); The compiler tries to match explicitly declared functions first, then try the template. If No match can be found, return +.
      • GNU's Not Unix! see www.gnu.org