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

标签 c++ arrays tuples c++14 constexpr

我目前正在寻找一种封装数据以供编译时访问的数据结构。因此,访问的值应该作为 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/

相关文章:

c++ - 为什么我观察到多重继承比单一继承要快?

c++ - 在 API 和应用程序线程之间共享数据

c++ - 使用 qsort 对 2D 数组进行排序 - 正确的类型转换

arrays - 如何在 ECLiPSe (CLP) 中将向量转换为数组? (或序言)

python - Python中元组的循环移动平均线

C++ 指针对象位置

c++ - c/c++ 禁用对文件的访问

php - 从数组中去除出现次数少于两次的所有元素

java - 线程 "main"java.lang.NoClassDefFoundError : org/javatuples/Unit 中出现异常

python - 从 Python 中的元组列表中查找相等的值