引自:https://blog.csdn.net/weixin_43795921/article/details/127224633
template <typename IdentifierType, class AbstractProduct,
class ProductCreator = AbstractProduct *(*)(),
class MapContainer = std::map<IdentifierType, ProductCreator>>
class Factory {
public:
bool Register(const IdentifierType &id, ProductCreator creator) {
return producers_.insert(std::make_pair(id, creator)).second;
}
bool Unregister(const IdentifierType &id) {
return producers_.erase(id) == 1;
}
void Clear() { producers_.clear(); }
bool Empty() const { return producers_.empty(); }
template <typename... Args>
std::unique_ptr<AbstractProduct> CreateObjectOrNull(const IdentifierType &id,
Args &&... args) {
auto id_iter = producers_.find(id);
if (id_iter != producers_.end()) {
return std::unique_ptr<AbstractProduct>(
(id_iter->second)(std::forward<Args>(args)...));
}
return nullptr;
}
template <typename... Args>
std::unique_ptr<AbstractProduct> CreateObject(const IdentifierType &id,
Args &&... args) {
auto result = CreateObjectOrNull(id, std::forward<Args>(args)...);
PUB_E_IF(!result, "Factory could not create Object of type : " << id);
return result;
}
private:
MapContainer producers_;
};
Factory<int, IShape> oFactory;
oFactory.Register(1, []()->IShape*{return new CircleShape("color")};
标签:case,std,return,C++,producers,_.,switch,const,id From: https://www.cnblogs.com/kinglxg/p/17541574.html