混合int并在通信缓冲区中浮动

mix int and float in communication buffer

本文关键字:缓冲区 通信 int 混合      更新时间:2023-10-16

我正在将int和浮点值加载到缓冲区,以传输数据。

一些示例:

void send_cmd_1(int y, int z, int a, int b)
{
    int buf[5];
    buf[0] = 1;   // command #1
    buf[1] = y;   // parameters for command #1
    buf[2] = z;
    buf[3] = a;
    buf[4] = b;
    queue_command(buf);   // function to queue command
}
send_cmd_2(float x, int a)
{
    int buf[3];
    buf[0] = cmd_id;
    buf[1] = float_to_int(x);
    buf[2] = a;
    queue_command(buf);
}

我有许多(超过60个)功能,可以使用命令ID,而某些值是intfloat值的混合物。参数的数据类型由要传输到的设备决定。 我无法控制这一点。在这些函数中的每个功能中,与上述类似的代码都执行以打包缓冲区,然后将缓冲区排成一个发送数据的线程。

我正在寻找一种更优雅的方式来做到这一点,而不是创建60个功能的蛮力方法,这些函数看起来像上述略有变化。

在我看来,变异模板可能是对此模式的一个很好的解决方案。

我希望语法最终得到类似的内容:

send_cmd_1(int y, int z, int a, int b)
{
    enqueue(1, y, z, a, b);
}
send_cmd_2(float x, int a)
{
    enqueue(2, x, a);
}

其中' enqueue()'是一个可命令ID的变量函数或模板,而intfloat值的混合物则以适当的顺序将参数包装到缓冲区中并调用queue_command()函数。p>我需要对顾问的样子的帮助。

template<typename... Args>
void enqueue(int cmd_id, Args... args)
{
    int buf[sizeof...(Args)]
    buf[0] = cmd_id;
    for (int i = 1; i < sizeof...(Args); i++)
    {
       // what goes here?
    }
    queue_command(buf);
}

对于它的价值,如果" Args"是正确顺序的数据结构,那么我真的不需要对此做任何事情。只要字节按正确顺序,我就可以排队。

    queue_command(args);

根据提议的解决方案,我最终得到了:

void enqueue(cmd_enum cmd_id, Args... args)
{
    int buf[sizeof...(Args)+1U]{static_cast<int>(cmd_id), *reinterpret_cast<int*>(&args)...};
    queue_command(buf);
}

这给了我我所追求的。

void send_cmd_1(int y, int z, int a, int b)
{
    enqueue(command_1_name, y, z, a, b);
}

尚未测试。如果它不起作用,我会发布更正。

不确定要理解您的要求,但我想您可以编写一组to_int()函数,例如

int to_int (int i)
 { return i; }
int to_int (float f)
 { return float_to_int(f); }

,只需如下写下您的variadic enqueue()函数

template <typename ... Args>
void enqueue (int cmd_id, Args ... args)
 {
   int buf[sizeof...(Args)+1U] { cmd_id, to_int(args)... };
   queue_command(buf);
 }

观察buf的尺寸的+1cmd_id

需要