Queue of operations
I'm creating a class for configuration file handling. The w开发者_运维技巧ay I want it to work is:
There's a queue that retains all the operations (insert data, erase data...), then, the method Commit
will apply all those changes.
My prototypes looks like that (all the settings on the file are stored into a STL map):
bool Insert(std::string const& key, std::string const& value);
bool Erase(std::string const& key);
So, I've tried to create an STL queue of pointer to functions, but the functions don't have the same number of arguments, and I don't know what to do...
You could create an Operation base class and then derive it twice to make Insert and Erase classes. You could then store pointers to the Operation class.
class Settings
{
public:
bool Insert(std::string const& key, std::string const& value)
{
m_operations.push_back(new Insert(key, value));
return true; //?
}
bool Erase(std::string const& key)
{
m_operations.push_back(new Erase(key));
return true; //?
}
bool Commit()
{
// You know what to do by now right ?
}
private:
class Operation
{
public:
virtual void Execute() = 0
}
class Insert : public Operation
{
public:
Insert(std::string const& key, std::string const& value) :
m_key(key), m_value(value) {}
void Execute() {...}
private:
std::string m_key;
std::string m_value;
}
class Erase : public Operation
{
public:
Erase(std::string const& key) : m_key(key) {}
void Execute() {...}
private:
std::string m_key;
}
std::queue<Operation*> m_operations;
std::map<std::string, std::string> m_settings;
}
Then you either make your operation classes friend of the settings class or you pass a ref to the map the operation should by applied on.
精彩评论