I'm developing a message system that has to be able to handle different types of messages with different fields and values depending on an ID unique to each type of message.
To do so I've created a base class msg_base
from which all other messages are derived. This class has a class (static
) method called make_msg
that handles the creation of the specific messages:
std::unique_ptr<msg_base> msg_base::make_msg_base(int id)
{
switch (id)
{
case 00:
return std::make_unique<msg_00>();
break;
default:
return std::make_unique<msg_01>();
break;
}
}
msg_00
and msg_01
are derived from msg_base. As you can see, I want this function to return an unique_ptr to a newly created object of the needed type. But when compiling I'm getting the following error:
msg_base.cpp: In static member function ‘static std::unique_ptr<msg_base> msg_base::make_msg_base(int)’:
msg_base.cpp:12:57: error: could not convert ‘std::make_unique(_Args&& ...) [with _Tp = msg_00; _Args = {}; typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<msg_00, std::default_delete<msg_00> >]()’ from ‘std::_MakeUniq<msg_00>::__single_object {aka std::unique_ptr<msg_00, std::default_delete<msg_00> >}’ to ‘std::unique_ptr<msg_base>’
return std::make_unique<msg_00>();
Shouldn´t this conversion be allowed? The msg_base
class has only default constructor and destructor.
I've tried creating explicit constructors and destructors for the derived classes, but it won't allow the conversion.
This is C++14 or more, so that shouldn't be the problem.
EDIT: As requested, I add more context:
This is the base class header:
class msg_base
{
protected:
int id;
public:
msg_base();
msg_base();
static std::unique_ptr<msg_base> make_msg_base(int id);
};
and these are the derived classes:
class msg_00 : msg_base
{
};
I've omitted fields and methods not related to the problem, but there are no constructor/destructor defined for the derived classes.