3

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.

Jafar Gh
  • 137
  • 2
  • 12

1 Answers1

1

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).

Luisjomen2a
  • 241
  • 2
  • 16
  • Thanks. I have another question that every value saved in redis with `set key value` is saved as string? I mean if i use `Type key` later, it always returns string for such these SET commands? – Jafar Gh Jan 22 '20 at 14:43
  • From what I've gathered here https://redis.io/commands/set strings are exclusively used for setting. If you mean to use it later with something like https://redis.io/commands/get then yes, the return would be a string. – Luisjomen2a Jan 22 '20 at 14:53