zoukankan      html  css  js  c++  java
  • c++函数模板

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sstream>

    using namespace std;

    template<typename T>
    int compare(const T &v1, const T &v2)
    {
      if (v1 < v2)
      {
        return -1;
      }
      if (v1 > v2)
      {
        return 1;
      }
      return 0;
    }

    template<class T>
    T absValue(T val)
    {

      return val > 0 ? val : -val;
    }

    template<typename T1,typename T2>
    T1& print_define(T1& t1, T2 val)
    {
      t1 << val;
      return t1;
    }

    template<typename T>
    const T& bigger(const T& v1, const T& v2)
    {
      return v1 > v2 ? v1:v2;
    }

    int main()
    {
      //int x1 = 4;
      //int x2 = 3;

      double x1 = 4.5;
      double x2 = 4.5;


      int rx = compare(x1, x2);
      cout << rx << endl;

      double val1 = -0.76;
      cout << absValue(val1)<< endl;

      double dval = -0.98;
      float fval = -12.3;
      string oristr = "this is a test";
      string desstr;
      ostringstream oss(desstr);
      ofstream outfile("result.txt");

      print_define(cout, -3) << endl;
      print_define(cout, dval) << endl;
      print_define(cout, fval) << endl;
      print_define(cout, oristr) << endl;

      print_define(outfile, -3) << endl;
      print_define(outfile, dval) << endl;
      print_define(outfile, fval) << endl;
      print_define(outfile, oristr) << endl;
      outfile.flush();
      outfile.close();

      cout << bigger(val1,dval)<< endl;

      system("pause");
      return 0;
    }

     -------------------------------------------------------------------------------

    0
    0.76
    -3
    -0.98
    -12.3
    this is a test

  • 相关阅读:
    第四章 利用函数实现指定的功能
    5-7 点到原点的距离(多态)
    5-2 宠物的生长(多态)
    5-7 学生cpp成绩统计
    5-6 学生CPP成绩计算
    php将远程图片下载保存到本地
    vs2010 调试快捷键
    vs2010 快捷键大全
    [C#] 使用Application.AddMessageFilter当做Form的热键
    C# 收发和处理自定义的WINDOWS消息
  • 原文地址:https://www.cnblogs.com/herd/p/10970086.html
Copyright © 2011-2022 走看看