Я пытаюсь построить фабричный метод с саморегистрацией на основе (https://www.codetg.com/article/7r1QnR43bm3ZogBJ.html),), который регистрирует логические операции. Но я не могу понять, как преобразовать std :: make_unique в std :: make_unique.Я всегда получаю одну и ту же ошибку:
return': cannot convert from 'std::unique_ptr<T1,std::default_delete<_Ty>>' to 'std::unique_ptr<LogicOperation,std::default_delete<_Ty>>
Я все еще новичок на тему уникального указателя, но я прочитал на cppreference.com
If T is a derived class of some base B, then std::unique_ptr<T> is implicitly convertible to std::unique_ptr<B>.
The default deleter of the resulting std::unique_ptr<B> will use operator delete for B,
leading to undefined behavior unless the destructor of B is virtual.
У меня естьпопытался вместо создания лямбда-функции использовать std :: move (), как показано в других примерах в stackoverflow, но это тоже не работает.
main
int main()
{
Signal a;
Signal b;
a.setState(1);
b.setState(0);
std::unique_ptr<LogicOperation> logic = LogicOperationFactory::Create("AND");
bool x[2] = { a.getState(), b.getState() };
bool y = logic->operation(x, 2); // do and operation
}
LogicOperation.h
class LogicOperation
{
public:
LogicOperation() = default;
virtual ~LogicOperation() = default;
public:
virtual bool operation(bool*, uint8_t count) = 0;
};
LogicOperationFactory.h:
using TCreateMethod = std::function<std::unique_ptr<LogicOperation>()>;
template<class T1>
static bool Register(const std::string name)
{
std::map<std::string, TCreateMethod>::iterator it;
it = s_methods.find(name);
if (it != s_methods.end())
return false;
s_methods[name] = []() -> std::unique_ptr<LogicOperation> {
// Constructs an object of type T and wraps it in a std::unique_ptr
return std::make_unique<T1>(); // use default constructor
};
return true;
}
LogicAndOperation.cpp
class LogicAndOperation :
public virtual LogicOperation
{
public:
LogicAndOperation() = default;
virtual ~LogicAndOperation() = default;
bool operation(bool* signals, uint8_t count) override;
private:
static bool s_registered;
};
bool LogicAndOperation::s_registered =
LogicOperationFactory::Register<LogicAndOperation>("AND");
Может кто-нибудь объяснить мне, как я могу сделать STD ::unique_ptr из производного класса (LogicAndOperation)?