Template functions模板函数

// template function for a simple addition function
template<typename T> // template parameter list
T Add(T a, T b) // function template name
{
return a+b;
}
// int example
int a = 2;
int b = 2;
int res = Add(a,b); // i.e. int Add(int, int)
// float example
float c = 2.2;
float d = 2.2;
float res2 = Add(c,d); // i.e. float Add(float, float)

 

————————————————————————————————————————————————

 

// template class.
template<typename T> // The parameter list
class Foo // The template name id
{
public:
// constructor
Foo(){}; // default
Foo(T val):iVal(val){}
// Modifiers & Accessors
void Set(T val){iVal=val;}
T Get()const {return iVal;}
private:
T iVal;
};
// in use
Foo<int> foo(0); // Builds an int iVal class
Foo<float> boo(0.0); // Builds a float iVal

 

————————————————————————————————————————————————

 

template <typename T, typename C>
class Bar : public Foo<T> // this is using a template
{
public:
// ...
private:
C iDerivedVal;
};
// in use
Bar<int, float> bar;
bar.Set(42);

 

————————————————————————————————————————————————

 

// Generic
template<typename T> // template parameter list
T Add(T a, T b) // function template name
{
return a+b;
}
// Specialization
// The empty parameter list tells the compiler it is dealing with
// a specialization:
template<>
char* Add<char*>(char* a,char* b) // Template argument list
{
return strcat(a,b);
}
// In use
char* res = Add<char*>("foo","bar"); // note different syntax
int n = Add(2,2); // calling the int version

 

 

————————————————————————————————————————————————

 

 

template<typename T, int size>
68 CLASS DESIGN AND INHERITANCE
class Foo
{
T iElements[size]; // an array of Ts
};
// In use
Foo<int,10> foo; // Creates an array of 10 integers

 

————————————————————————————————————————————————————

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值