我对以下代码有问题(这是一个非常简单的例子,
#include <iostream>
using namespace std;
template<class T> class CBase
{
public:
template <class T2> CBase(const T2 &x) : _var(x) {;}
template <class T2> CBase (const CBase<T2> &x) {_var = x.var();}
~CBase() {;}
T var() const {return _var;}
protected:
T _var;
};
template<class T> class CDerived : public CBase<T>
{
public:
template <class T2> CDerived(const T2 &x) : CBase<T>(x) {;}
template <class T2> CDerived (const CBase<T2> &x) : CBase<T>(x) {;}
~CDerived() {;}
};
int main()
{
CBase<double> bd(3);
CBase<int> bi(bd); // <- No problem
CDerived<double> dd1(3);
CDerived<double> dd2(dd1);
CDerived<int> di(dd1); // <- The problem is here
return 0;
}
错误如下:
error: cannot convert const CDerived<double> to int in initialization
如何解决这个问题? (优先修改基类而不是衍生类,如果可能,也不使用虚拟性)
非常感谢你
EDIT :
If I replace the concerned line with : CDerived<int> di(CBase<int>(CBase<double>(dd1)));
it works but it is not very practical...
看来解决的方法是:
template <class T2> CDerived(const CDerived<T2> &x) : CBase<T>(static_cast<const CBase<T2>&>(x)) {;}