I have a problem with the following code fragment (this is a very simplified example that reproduces an error in my program):
#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; }
And the error is as follows:
error: cannot convert 'const CDerived<double>' to 'int' in initialization
How to solve this? (with the preference for changes in the base class, rather than in the derived class, and, if possible, without the use of virtuality)
Many thanks
EDIT: If I replace the corresponding line: CDerived<int> di(CBase<int>(CBase<double>(dd1)));
It works, but it is not very practical ...
EDIT: It seems to solve the following:
template <class T2> CDerived(const CDerived<T2> &x) : CBase<T>(static_cast<const CBase<T2>&>(x)) {;}
source share