在旧的 C 头文件中,我有以下映射(32 行):
#define IOCON_INDEX_PIO0_17 ( 0)
#define IOCON_INDEX_PIO0_13 ( 1)
#define IOCON_INDEX_PIO0_12 ( 2)
//...
Run Code Online (Sandbox Code Playgroud)
在 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];
}
};
Run Code Online (Sandbox Code Playgroud)
但是当我查看程序集生成的代码时,它似乎很大。我也想知道它将使用什么 RAM。
我必须使用符合 C++14 的编译器,所以:
constexpr 可能是答案的一部分...
[编辑] 我不想替换C 代码,而是将其调整为具有一个将 int 作为参数并返回另一个 int 的函数。它在一个小型嵌入式系统上运行,所以我希望它尽可能紧凑(在闪存和 RAM 方面)。
使用 c++17 更改
const std::array<int, 32> iocon_index = [](){
std::array<int, 32> buf;
Run Code Online (Sandbox Code Playgroud)
到
constexpr std::array<int, 32> iocon_index = []() {
std::array<int, 32> buf { };
Run Code Online (Sandbox Code Playgroud)
似乎解决了程序集大小问题(-O2 和 -Os)
在 c++14 中,您可以使用 constexpr 函数而不是 lambda 来初始化数组。
编辑:在 c++14 中
std::array不可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)
...
Run Code Online (Sandbox Code Playgroud)
EDIT2:
为了使它更具可读性,可以做
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;
};
Run Code Online (Sandbox Code Playgroud)
进而
std::array<int, 32> buf2 { };
array_assign buf(buf2);
buf[17] = 0;
buf[13] = 1;
buf[12] = 2;
...
return buf2;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |