I am stuck with an object slicing problem when using CRTP. The following mock illustrates my problem.
#include <memory>
class CrtpGenr
{
};
template<class t_object>
class CrtpBase : public CrtpGenr
{
public:
static
auto create() -> std::unique_ptr<t_object> {
return(std::unique_ptr<t_object>(new t_object));
}
void funct1(){}
};
class CrtpDirv1 : public CrtpBase<CrtpDirv1>
{
public:
void funct2(){}
};
class CrtpDirv2 : public CrtpBase<CrtpDirv2>
{
public:
void funct2(){}
};
int main()
{
/*
// This works
std::unique_ptr<CrtpDirv1> crtp_obj = CrtpDirv1::create();
crtp_obj->funct1();
crtp_obj->funct2();
*/
std::unique_ptr<CrtpGenr> crtp_obj1 = static_cast<std::unique_ptr<CrtpGenr>>(CrtpDirv1::create());
std::unique_ptr<CrtpGenr> crtp_obj2 = static_cast<std::unique_ptr<CrtpGenr>>(CrtpDirv2::create());
crtp_obj1->funct1();
crtp_obj1->funct2();
return 0;
}
Compiling the above code gives me the following error:
main.cpp: In function 'int main()':
main.cpp:47:16: error: 'class CrtpGenr' has no member named 'funct1'
crtp_obj1->funct1();
^
main.cpp:48:16: error: 'class CrtpGenr' has no member named 'funct2'
crtp_obj1->funct2();
I would like to be able to cast the CrtpDirv1 and CrtpDirv2 classes to CrtpGenr. This is so that I can define a container of type CrtpGenr to hold objects of either CrtpDirv1 or CrtpDirv2. What am I doing wrong?