gpt4 book ai didi

c++ - 带 get 的数据结构,返回一个 constexpr (C++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:16:32 24 4
gpt4 key购买 nike

我目前正在寻找一种封装数据以供编译时访问的数据结构。因此,访问的值应该作为 constexpr 返回。

虽然元组确实具有 constexpr 构造函数,但元组的 get 函数不返回 constexpr。

是否存在这样的数据结构,或者是否可以手动定义这样的数据结构?

最终目标是将编译时已知值打包到某种对象中,将其(通过模板)传递给函数,访问那里的元素并将编译时已知值作为常量直接粘贴到二进制文件中。就我的目的而言,封装部分至关重要。

最佳答案

从 C++14 开始,std::tuple 确实接受 constexpr std::get

#include <tuple>

int main()
{
constexpr std::tuple<int, int, int> t { 1, 2, 3 };
static_assert(std::get<0>(t) == 1, "");
}

Live Example

同样,您也可以将 std::arraystd::get 一起使用(而且 operator[] 现在是 constexpr)。原始 C 数组也可以完成。

#include <array>

int main()
{
constexpr std::array<int, 3> a {{ 1, 2, 3 }};
static_assert(std::get<0>(a) == 1, "");
static_assert(a[0] == 1, "");
}

Live Example

关于c++ - 带 get 的数据结构,返回一个 constexpr (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32117925/

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