I am new to redis. I want to write a simple library (for testing) that is on top level of the hiredis. for example to implement SET command I wrote the code bellow:
#include<iostream>
#include<type_traits>
#include<hiredis.h>
#include<string>
using namespace std;
template<typename T>
string set(string key, T value)
{
/* set a key */
if(is_same<T, int>::value)
{
reply = (redisReply*) redisCommand(c, "SET %s %d", key, value) // c is redisContext*
}
else if(is_same<T, string>::value)
{
reply = (redisReply*) redisCommand(c, "SET %s %s", key, value)
}
// and so on for other data types ...
string replyStr = reply->str;
freeReplyObject(reply);
return replyStr;
}
is there any better solution to handle different data types as Value for SET command? (I mean avoiding using If statements for each datatype ). regards.
If I understand correctly, you only need to know the type of value
in order to know what type you are inserting in your redisCommand
string as your write your reply.
If you are restricting these types to basic types try calling to_string
on value
in order to build a result std::string
for more information https://en.cppreference.com/w/cpp/string/basic_string/to_string don't forget the include of course!
something like this :
template<typename T>
string set(string key, T value)
{
std::string result(std::string("SET ") + to_string(key) + to_string(value));
reply = (redisReply*) redisCommand(c, result);
string replyStr = reply->str;
freeReplyObject(reply);
return replyStr;
}
EDIT : Another viable solution would be to simply cast your variable each time you call 'set' and simply rewrite your function as string set(string key, string value)
.