23.4.6 Member Templates---The C++ Programming Language 4th Edition

 [vs2013都能编过噢]

Be warned that the narrowing error in the complex<double> to complex<float> case will not be
caught until the instantiation of complex<float>’s template constructors and then only because I used
the {} initialization syntax (§6.3.5) in the constructor’s member initializers. That syntax does not
allow narrowing.


template<typename Scalar>
class complex {
 Scalar re, im;
public:
 complex() :re{}, im{} {} // default constructor
 template<typename T>
 complex(T rr, T ii = 0) : re{ rr }, im{ ii } { }
 complex(const complex&) = default; // copy constr uctor
 template<typename T>
 complex(const complex<T>& c) : re{ c.real() }, im{ c.imag() } { }
 // ...
};

complex<float> cf3{ 2.0, 3.0 };

//
//template<typename Scalar>
//class complex { // old style
// Scalar re, im;
//public:
// complex() :re(0), im(0) { }
// template<typename T>
// complex(T rr, T ii = 0) : re(rr), im(ii) { }
// complex(const complex&) = default; // copy constr uctor
// template<typename T>
// complex(const complex<T>& c) : re(c.real()), im(c.imag()) { }
// // ...
//};
//complex<float> cf4{ 2.1, 2.9 }; // ouch! narrows

posted @ 2014-06-10 11:12  fbwang2011  阅读(95)  评论(0编辑  收藏  举报