【问题标题】:efficient handling of creating a template for SET command of redis (hiredis)高效处理为 redis (hiredis) 的 SET 命令创建模板
【发布时间】:2020-01-22 13:54:35
【问题描述】:

我是 redis 的新手。我想编写一个位于hiredis顶层的简单库(用于测试)。 例如为了实现 SET 命令,我编写了以下代码:

#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;     
}

有没有更好的解决方案来处理不同的数据类型作为 SET 命令的值? (我的意思是避免对每种数据类型使用 If 语句)。 问候。

【问题讨论】:

    标签: c++ templates redis refactoring hiredis


    【解决方案1】:

    如果我理解正确,您只需要知道value 的类型,就可以知道您在写回复时在redisCommand 字符串中插入了什么类型。

    如果您将这些类型限制为基本类型,请尝试在 value 上调用 to_string 以构建结果 std::string

    更多信息https://en.cppreference.com/w/cpp/string/basic_string/to_string 当然不要忘记包含!

    类似这样的:

    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;     
    }
    

    编辑:另一个可行的解决方案是在每次调用“set”时简单地转换变量,并将函数重写为string set(string key, string value)

    【讨论】:

    • 谢谢。我还有一个问题,使用set key value 保存在redis 中的每个值都保存为字符串?我的意思是如果我稍后使用Type key,它总是为这些 SET 命令返回字符串?
    • 从我在这里收集到的redis.io/commands/set 字符串专门用于设置。如果您打算稍后将它与redis.io/commands/get 之类的东西一起使用,那么是的,返回将是一个字符串。
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2020-12-28
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多