注册 登录
编程论坛 C++教室

写一个模板函数T max(T x1, T x2)求两个数中大的数,并对整数(int类型)模板特例化,返回小的数。

遗情处有诗章 发布于 2018-05-28 09:46, 1345 次点击

求助 代码错误怎么改

#include<iostream>

#include<stdlib.h>

#include <cstring>

using namespace std;

template<typename T>

T max(T x, T y) {

   return (x > y) ? x : y;

}

void main() {

   float x1 = 2.3, y1 = 3.2;

   int x2 = 2, y2 = 1;

   cout << "max(x1,y1) = " <<max(x1, y1) << endl;

   cout << "max(x2,y2) = " <<max(x2, y2) << endl;

   system("pause");

}
2 回复
#2
rjsp2018-05-28 12:21
程序代码:
template<class T>
constexpr const T& max( const T& a, const T& b )
{
    return (a < b) ? b : a;
}

template<>
constexpr const int& max( const int& a, const int& b )
{
    return (b < a) ? b : a;
}

#include <iostream>
using namespace std;

int main( void )
{
    cout << ::max(1.1, 2.2) << endl;
    cout << ::max(111, 222) << endl;
}

假如你用的是上个世纪的编译器,将 constexpr 去掉即可。
1