常见错误88:对模板化的复制操作的认识误区
对于模板成员函数的一个普通用途是用于实现构造函数。很多标准库中的容器组件都会有个
模板化的构造函数,这样就允许使用一个元素序列来初始化该容器:
模板化的构造函数的运用使得容器能够接受任意类型的输入序列,若非如此,容器类型之
实用性也就大打折扣。而标准库中的auto_ptr模板组件亦使用模板成员函数:
对于模板成员函数的一个普通用途是用于实现构造函数。很多标准库中的容器组件都会有个
模板化的构造函数,这样就允许使用一个元素序列来初始化该容器:
模板化的构造函数的运用使得容器能够接受任意类型的输入序列,若非如此,容器类型之
实用性也就大打折扣。而标准库中的auto_ptr模板组件亦使用模板成员函数:
模板成员函数绝不会为完成赋值操作而实例化。
money.h
#ifndef MONEY_H
#define MONEY_H
enum Currency { CAD, DM, USD, Yen };
class Curve {
public:
Curve( Currency )
{}
double convert( Currency, Currency, double amt ) const
{ return amt; }
};
template <Currency currency>
class Money {
public:
Money( double amt );
template <Currency otherCurrency>
Money( const Money<otherCurrency> & );
template <Currency otherCurrency>
Money &operator =( const Money<otherCurrency> & );
~Money();
double get_amount() const
{ return amt_; }
//...
private:
Curve *myCurve_;
double amt_;
};
template <Currency currency>
Money<currency>::Money( double amt )
: myCurve_( new Curve(currency) ), amt_(amt) {}
template <Currency currency>
Money<currency>::~Money()
{ delete myCurve_; }
template <Currency currency>
template <Currency otherCurrency>
Money<currency>::Money( const Money<otherCurrency> &that )
: myCurve_( new Curve(currency) ), amt_(myCurve_->convert(currency,otherCurrency,that.get_amount())) {}
template <Currency currency>
template <Currency otherCurrency>
Money<currency> &Money<currency>::operator =( const Money<otherCurrency> &rhs ) {
amt_ = myCurve_->convert( currency, otherCurrency, rhs.get_amount() );
return *this;
}
#endif
money.cpp
无内容
main.cpp
#include "money.h"
#include<iostream>
int main() {
Money<Yen> acct1( 1000000.00 );
Money<DM> acct2( 123.45 );
Money<Yen> acct3( acct2 ); // template ctor
Money<Yen> acct4( acct1 ); // compiler-generated copy ctor!
acct3 = acct2; // template assignment
acct4 = acct1; // compiler-generated assignment!
getchar();
return 0;
}
输出
无输出