我有一个Derived
继承自 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;
}
};
我想创建一个创建类型对象的工厂Derived
。我当然可以用函数来做到这一点:
template <typename ResourceType>
auto derived_factory () {
return new Derived<ResourceType>();
}
auto derived = *(derived_factory<int>());
但是,我无法为工厂编写 lambda 函数。如果我使用 auto 关键字接受模板参数,我可以编写模板化的 lambda 函数,但在这里我只想使用模板来确定返回类型。以下失败:
auto derived_factory = []<typename ResourceType>() {
return new Derived<ResourceType>();
};
auto derived = *(derived_factory<int>());
出现错误:
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’
我只是错误地调用了 lambda 吗?还是我必须等待C++20
?