I have the following overloaded functions. All the code is the same as except for their format (%s
v.s %lu
), so I couldn't use templates.
Should I implement generic programming like this?
Edited : Actually I'm executing redisCommand()
in set()
bool set(const string& key, const string& value)
{
// some codes for input check
redisCommand("SET %s %s", key.c_str(), value.c_str());
// some codes for making return value
}
bool set(const string& key, unsigned long value)
{
// some codes for input check
redisCommand("SET %s %lu", key.c_str(), value);
// some codes for making return value
}
Both key and value might have space or double quotes.
set("my key", "my value");
set("my \"key2", 12345);
set("my key3", "my \"value2");
I would like to change set()
as follows.
template <typename T>
bool set(const string& key, const T& value)
{
// some codes for input check
std::ostringstream cmd;
cmd << "SET \"" << escape_func(key) << "\" \""
<< escape_func(value) << "\"";
redisCommand(cmd.c_str());
// some codes for making return value
}
template <typename T>
const T escace_func(const T& v)
{
return v;
}
template<>
const string escape_func(const string& str)
{
replace all " to \" and return;
}
Any suggestion would be appreciated.
std::stringstream
will pretty much solve this problem for you. – Yuushi yesterday