function template,函数模板

本文介绍了函数模板的概念,并通过示例展示了如何使用函数模板实现通用的最小值函数。该示例包括了基本的数据类型以及自定义类型stone的应用。通过本文,读者可以了解到函数模板的基本用法及其在实际编程中的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function template,函数模板


一、函数模板概念

函数模板指的是函数参数类型和返回类型的参数化。

二、示例代码

	template<class T>
    inline
    const T& min(const T& a, const T& b)
    {
        return b < a ? b : a;
    }

    class stone
    {
    public:
        stone(int w, int h, int we)
        : _w(w), _h(h), _weight(we)
        {  }
        int get_w() const { return _w; }
        int get_h() const { return _h; }
        int get_weight() const { return _weight; }
        bool operator< (const stone& rhs) const
        { return _weight < rhs._weight; }
    private:
        int _w, _h, _weight;
    };

    ostream &
    operator << (ostream& os, const stone& x)
    {
        return os << '(' << x.get_w() << ',' << x.get_h() << ')' << "  " << x.get_weight();
    }
    void test_function_template()
    {
        std::cout << min(4,10) << std::endl;
        stone s1(5, 5 ,20);
        stone s2(6, 6, 30);
        std::cout << min(s1,s2) << std::endl;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值