Maybe this is a simple question, because I'm still new to C++. I would like to use some kind of factory to encapsulate the logging in my application. The idea is that only the factory knews which concrete class will handle the function calls. The application will always call abstract interfaces of the base logging class.
The factory method should look like:
std::unique_ptr<AbstractLoggingClass> Factory::getDefaultLogger(const std::string& param){
return new ConcreteLoggingClass(param);
}
ConcreteLoggingClass
is a subclass of AbstractLoggingClass
.
But I get the following error:
Error: could not convert '(operator new(64ul), (<statement>,
((ConcreteLoggingClass*)<anonymous>)))' from 'ConcreteLoggingClass*'
to 'std::unique_ptr<AbstractLoggingClass>'
My problem is that I don't know how to instantiate ConcreteLoggingClass
and return a unique_ptr
to AbstractLoggingClass
I already found this post , but I still don't see the solution.
The std::unique_ptr
constructor you want is explicit
, hence you need to be... well... explicit about it. Try
return std::unique_ptr<AbstractLoggingClass>(new ConcreteLoggingClass(param));
If you can use C++14 you should use std::make_unique
:
return std::make_unique<ConcreteLoggingClass>( param );
otherwise explicitly create std::unique_ptr
:
return std::unique_ptr<AbstractLoggingClass>{ new ConcreteLoggingClass{param}};
The constructor of std::unique_ptr<T>
is explicit
. It won't implicitly convert from a pointer as doing so would mean a pointer is silently deleted.
You can return a std::unique_ptr<T>
explicitly constructing it, eg:
return std::unique_ptr<AbstractLoggingClass>(new ConcreteLoggingClass(param));
You can't convert your pointer to a unique_ptr
, you have to create it :
std::unique_ptr<AbstractLoggingClass> Factory::getDefaultLogger(const std::string& param){
return std::unique_ptr<AbstractLoggingClass>(new ConcreteLoggingClass(param));
}
if you have c++14 or better:
std::unique_ptr<AbstractLoggingClass>
Factory::getDefaultLogger(const std::string& param)
{
return std::make_unique<ConcreteLoggingClass>(param);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.