I have a class Derived
that inherits from class Base<ResourceType>
:
template <class ResourceType>
class Base {
protected:
ResourceType* resource;
public:
void set_resource(ResourceType* resource) {
this->resource = resource;
}
};
template <class ResourceType>
class Derived : public Base<ResourceType> {
public:
using Base<ResourceType>::resource;
void print () {
std::cout << *resource << std::endl;
}
};
I want to create a factory that creates objects of type Derived
. I can of course do this with functions:
template <typename ResourceType>
auto derived_factory () {
return new Derived<ResourceType>();
}
auto derived = *(derived_factory<int>());
But, I am not able to write a lambda function for the factory. I can write templated lambda functions if I was accepting a template argument using the auto keyword, but here I just want to use the template to determine the return type. The following fails:
auto derived_factory = []<typename ResourceType>() {
return new Derived<ResourceType>();
};
auto derived = *(derived_factory<int>());
with the error:
inherit_unknown_type.cpp: In function ‘int main()’:
inherit_unknown_type.cpp:27:36: error: expected primary-expression before ‘int’
auto derived = *(derived_factory<int>());
^~~
inherit_unknown_type.cpp:27:36: error: expected ‘)’ before ‘int’
Am I just calling the lambda incorrectly? Or do I have to wait for C++20
?