【C++】member template function 成员模板函数

本文介绍了如何在C++中定义模板成员函数,并通过实例展示了如何使用它来输出不同类型的元素到输出流。

 

It is also possible to define a member template function. Let's look at an example and then walk through it:

 

class PrintIt { 
public: 
    PrintIt( ostream &os ) 
           : _os( os ){} 
    // a member template function 
    template <typename elemType> 
    void print( const elemType &elem, char delimiter = '\n' ) 
              { _os << elem << delimiter; } 
private: 
    ostream& _os; 
}; 

PrintIt is a nontemplate class that is initialized to an output stream. It provides a member template print() function that writes an object of an arbitrary type to that output stream. By making print() a member template function, we can provide a single instance that supports any type for which an instance of the output operator can be applied. Were we to parameterize PrintIt by the type of element we wish to output, we would create a new class template for each distinct type. Under this implementation, there is only a single PrintIt class. Here is how we might use it:

 

int main() 
{ 
    PrintIt to_standard_out( cout ); 
    to_standard_out.print( "hello" ); 
    to_standard_out.print( 1024 ); 
    string my_string( "i am a string" ); 
    to_standard_out.print( my_string ); 
} 

When compiled and executed, this generates the following output:
hello
1024
i am a string


A template class can also define a member template function. For example, we might parameterize PrintIt by its ostream type while maintaining print() as a member template function:

 

template <typename OutStream> 
class PrintIt { 
public: 
    PrintIt( OutStream &os ) 
           : _os( os ){} 
    template <typename elemType> 
    void print( const elemType &elem, char delimiter = '\n' ) 
              { _os << elem << delimiter; } 
private: 
    ostream& _os; 
}; 
//Here is our modified program:
int main() 
{ 
    PrintIt<ostream> to_standard_out( cout ); 
    to_standard_out.print( "hello" ); 
    to_standard_out.print( 1024 ); 
    string my_string( "i am a string" ); 
    to_standard_out.print( my_string ); 
} 
 
  
 
  

Author: visayafan <visayafan@gmail.com>

Date: 2011-11-27 22:13:37

HTML generated by org-mode 6.33x in emacs 23

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值