I need to override the method createT() of a Base template class with the one in a Derived template class with a different number of input parameters. I've developed this very simple example:
#include <iostream>
class Helper
{
public:
Helper(std::string s): _s(s)
{}
void display()
{
std::cout << _s << std::endl;
}
private:
std::string _s;
};
class Helper2
{
public:
Helper2(std::string s, int i):
_s(s), _i(i)
{}
void display()
{
std::cout << _s << " + " << std::to_string(_i) << std::endl;
}
private:
std::string _s;
int _i;
};
template<class T> class Base
{
public:
Base()
{
_pTBase = createT();
}
void test()
{
_pTBase->display();
}
protected:
/// Subclasses can override this method.
virtual T* createT()
{
return new T("### BASE ###");
}
private:
T* _pTBase;
}; //template<class T> class Base
template<class T> class Derived : public Base<T>
{
public:
Derived() : Base<T>()
{
_pTDerived = createT();
}
void test()
{
_pTDerived->display();
}
protected:
virtual T* createT()
{
return new T("### DERIVED ###", 5);
}
private:
T* _pTDerived;
}; //template<class T> class Derived : public Base<T>
int main()
{
Derived<Helper2> a;
a.test();
return 0;
}
When I try to compile i receive this message:
error: no matching function for call to ‘Helper2::Helper2(const char [13])’
return new T("### BASE ###");
^
It seems that the compiler cannot use the createT() method in the derived class Of course everything works correctly if I use the Base class with the Helper (not the Helper2) class. What's the right way to solve this situation?
Best regards
Aucun commentaire:
Enregistrer un commentaire