C++ Template Instantiate Sample

来源:互联网 发布:淘宝如何发货 编辑:程序博客网 时间:2024/06/06 12:48

 

 

 

#include <iostream>
using namespace std;

// template <class T>

template <typename T>
inline T square(T x)
{
   T result;

   result = x * x;

   return result;
};

// template specialization
template <>
string square<string>(string s)
{
   return (s + s);
};

int main(int argc, char **argv)
{
   string str("Avatar");

   int    i, ii;
   float  f, ff;
   double d, dd;

   i = 3, f = 33.333, d = 3.1415926;

   ii = square<int>(i);
   cout << i << " * " << i << " = " << ii << endl;

   ff = square<float>(f);
   cout << f << " * " << f << " = " << ff << endl;

   dd = square<double>(d);
   cout << d << " * " << d << " = " << dd << endl;

   // Implicit
   dd = square(d);
   cout << d << " * " << d << " = " << dd << endl;

   cout << square<string>(str) << endl;
}

 

 

1 0
原创粉丝点击