gpt4 book ai didi

c++ - 如何使用现代 C++ 调整旧 C 风格的#define 映射?

转载 作者:行者123 更新时间:2023-12-01 14:36:43 26 4
gpt4 key购买 nike

在旧的 C 头文件中,我有以下映射(长 32 行):

#define    IOCON_INDEX_PIO0_17       ( 0)
#define IOCON_INDEX_PIO0_13 ( 1)
#define IOCON_INDEX_PIO0_12 ( 2)
//...

在 C++ 中,我可以有一个接受索引并返回 int 的函数。为此,我将仅在一行中初始化一个数组,但它的可读性不高。

我想用具有现代风格的 C++ 替换它。我想过像这样使用 lambda 的东西:

#include <array>
class test
{
int icon_index(int pio_index)
{
const std::array<int, 32> iocon_index = [](){
std::array<int, 32> buf;
buf[17] = 0;
buf[13] = 1;
buf[12] = 2;
//...
return buf;
}();
return iocon_index[pio_index];
}
};

但是当我查看 assembly generated code ,似乎很大。我也想知道它将使用什么 RAM。

我必须使用兼容 C++14 的编译器,所以:

  1. 用 C++14 替换此遗留 C 代码的最佳方式是什么?
  2. 用 C++17 替换此遗留 C 代码的最佳方式是什么?

constexpr 可能是答案的一部分...

[edit] 我不想替换 C 代码,而是对其进行调整以使其具有一个将 int 作为参数并返回另一个 int 的函数。它在一个小型嵌入式系统上运行,所以我希望它尽可能紧凑(在闪存和 RAM 方面)。

最佳答案

使用c++17改变

const std::array<int, 32> iocon_index = [](){
std::array<int, 32> buf;

constexpr std::array<int, 32> iocon_index = []() {
std::array<int, 32> buf { };

似乎解决了程序集大小问题(-O2 和 -Os)

在 c++14 中,您可以使用 constexpr 函数代替 lambda 来初始化数组。

编辑:
std::array 在 c++14 中不可修改 constexpr。这是规避该问题的肮脏方法

std::array<int, 32> buf { };
const auto& as_const = buf;

const_cast<int&>(as_const[17]) = 0; //operator[](size_type) const is constexpr
const_cast<int&>(as_const[13]) = 1; //but not operator[](size_type)
...

编辑2:
为了使其更具可读性,可以这样做

struct array_assign
{
constexpr
array_assign(std::array<int, 32>& arr) :
arr(arr)
{ }

constexpr int& operator[](std::size_t idx)
{
return const_cast<int&>(this->arr[idx]);
}

const std::array<int, 32>& arr;
};

然后

std::array<int, 32> buf2 { };
array_assign buf(buf2);

buf[17] = 0;
buf[13] = 1;
buf[12] = 2;
...
return buf2;

关于c++ - 如何使用现代 C++ 调整旧 C 风格的#define 映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62511157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com