Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用于将列表重新指定给数组的一个线性快捷方式_C++_C++17 - Fatal编程技术网

C++ 用于将列表重新指定给数组的一个线性快捷方式

C++ 用于将列表重新指定给数组的一个线性快捷方式,c++,c++17,C++,C++17,如何使用C++17功能优雅地简化(或消除)下面代码中循环的 #pragma pack(push, 1) typedef struct ethernet_frame { unsigned char dst[6]; unsigned char src[6]; unsigned short proto; } ethernet_frame, *ethernet_frame

如何使用C++17功能优雅地简化(或消除)下面代码中循环的

#pragma pack(push, 1)
        typedef struct ethernet_frame
        {
            unsigned char   dst[6]; 
            unsigned char   src[6]; 
            unsigned short  proto;
        } ethernet_frame, *ethernet_frame_ptr;
#pragma pack(pop)

        int i;
        ethernet_frame eFrame = { {00,00,00,00,00,00}, {42, 54, 33, 67, 14, 88}, 0x800 };
        ProcessFrame(&eFrame); //A library function expecting an address of an ethernet_frame with its strict bit layout

        i = 0;
        for (unsigned char c : { 36, 84, 23, 77, 35, 11 }) eFrame.dst[i++] = c;
        ProcessFrame(&eFrame);

        i = 0;
        for (unsigned char c : { 65, 23, 74, 82, 20, 94 }) eFrame.dst[i++] = c;
        ProcessFrame(&eFrame);

        i = 0;
        for (unsigned char c : { 47, 22, 86, 45, 33, 38 }) eFrame.dst[i++] = c;
        ProcessFrame(&eFrame);

        // etc...

eFrame.Dst={47,22,86,45,33,38}
这样的重新分配会很整洁……但它们是非法的:(

如果不能将
struct ethernet\u frame
更改为使用
std::array
,那么仍然可以使用几个单行程序来复制数据,尽管安全性较差。首先,使用好的
memcpy()

使用,您可以避免指定要复制的数据的大小:

#include <experimental/ranges/algorithm>
...
std::experimental::ranges::copy(std::array<unsigned char, 6>{36, 84, 23, 77, 35, 11}, eFrame.dst);
#包括
...
std::experimental::ranges::copy(std::array{36,84,23,77,35,11},eFrame.dst);

此外,如果您想多次使用的东西没有一个线性函数,那么您当然可以自己编写一个函数,将问题转化为一个线性函数。

不是真正的一个线性函数,而是一个使用C++17倍表达式的简单函数:

template<typename... Ts, typename T>
void set_elements(T (&arr)[sizeof...(Ts)], Ts... values) {
    auto ptr = arr;
    ((*ptr++ = values), ...);
}

为什么不使用
std::array
?@Algirdas:因为我无法确定
std::array
在内存中的排列方式。以太网帧必须具有非常特定的位布局。“因为我无法确定
std::array
在内存中的排列方式。”为什么这是个问题?@Algirdas:因为一个
以太网帧
必须有一个非常特定的位布局才能通过网络传输。请看:是的,但我不能从中得出结论,填充没有添加。如果是,那么它将破坏
以太网帧的布局
也可以使用
std::copy
吗?不,
std::复制
需要一个开始迭代器和结束迭代器,不可能用一条语句来完成。使用逗号运算符和副作用…它既可怕又简单:)
#include <experimental/ranges/algorithm>
...
std::experimental::ranges::copy(std::array<unsigned char, 6>{36, 84, 23, 77, 35, 11}, eFrame.dst);
template<typename... Ts, typename T>
void set_elements(T (&arr)[sizeof...(Ts)], Ts... values) {
    auto ptr = arr;
    ((*ptr++ = values), ...);
}
set_elements(eFrame.dst, 36, 84, 23, 77, 35, 11);