我目前正在寻找一种封装数据的数据结构,以便进行编译时访问。因此,访问的值应作为constexpr返回。
虽然元组确实有一个constexpr构造函数,但元组的get
函数不会返回constexpr。
是否存在这样的数据结构,或者是否可以手动定义这样的数据结构?
最终目标是在某种对象中打包编译时已知值,将其(通过模板)传递给函数,访问那里的元素,并将编译时已知值直接粘贴到二进制文件中作为常量。为了我的目的,封装部分至关重要。
答案 0 :(得分:1)
从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, "");
}
同样,您可以std::array
使用std::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, "");
}